Top

Create New Page


To create a page we need to create modules and components, and write some import lines in few files, but fortunately Angular provides commands to automate this task. In this guide we will see how to use them.


Creating a Module


First we will navigate to the app folder and according to the nature of the page you are about to create , make a folder with suitable name. For example, if you are creating a page related to the authentication then we will create a module inside auth folder.


Now that we are at the proper place, Open that folder in the terminal and execute the below given command:


ng generate module module_name

This will create a folder with name module_name, inside that folder 2 files will be created module_name.routing.module.ts and module_name.module.ts.

In our routes.ts file, we will import this module and give a path to it. To know more about routing follow our Guide to Routing.


The path for this module in routes.ts file will look something like this.

import { Routes } from '@angular/router';

 export const content: Routes = [
    {
     path: 'new_Module_path',
     loadChildren: () => import('relative_path_for_module/module_name.module').then(m => m.Module_nameModule)
    },
]

Creating a New Component


Now to create pages inside this module we will run the below given command:


ng generate component component_name

Info: Did you know that you can create module with just ng g m module_name and similarly create component with ng g c component_name.

ng generate component component_name --skip-tests

Info: Here angular has created a .scss file for styling because when installing the project we selected scss language for our styles. You can select css or any other language of your choice to style your theme, but make sure you do that while you are installing the project.

Adding route

Now that we have created our component, to display this component in our browser we need to provide a route for it and attach this component to that route.

We will navigate to the module_name-routing.module.ts file and create our route there. So the route for our newly create component will look something like this.

import { component_name } from './component_name/component_name';
  const routes: Routes = [
    {
      path: 'componentPath',
      component: Component
     },
  ]

This was for a single component, but if you create multiple components in a single module and want to give paths for them, it will look something like this:


import { component_name1 } from './component_name1/component_name1';
import { component_name2 } from './component_name2/component_name2';
const routes: Routes = [
        {
        path: 'parentPath',
        children: [
          {
            path: 'childPath1',
            component: component_name1
          },
          {
            path: 'childPath2',
            component: component_name2
          },
        }
    ]