Create New Page
To create a page we need to create routes 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.
In Angular standalone, without using Angular CLI, you typically create modules and routing manually. If you want to create a new routing file according to your folder name, you would follow these steps:.
Create a Routing File:
Suppose you have a folder named example, and you want to create a routing file for it. You can create a file named example.routes.ts within the example folder.
Define Routes:
In the example.routes.ts file, you define the routes specific to the example module. Here's an example of how you might define routes:
import { Routes } from '@angular/router';
import { Example } from './example';
export const ExampleRoutes: Routes = [
{
path: '',
component: Example
},
// Define other routes as needed
];
Creating a New Component
Now to create pages inside this routes we will run the below given command:
ng generate component component_name
Info: Did you know that you can create routes with 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.
import { Routes } from '@angular/router';
import { component_name } from './component_name/component_name';
export const _name routes: Routes = [
{
path: 'componentPath',
component: Component
},
]
This was for a single component, but if you create multiple components in a single routes and want to give paths for them, it will look something like this:
import { Routes } from '@angular/router';
import { component_name1 } from './component_name1/component_name1';
import { component_name2 } from './component_name2/component_name2';
export const _name routes: Routes = [
{
path: 'parentPath',
children: [
{
path: 'childPath1',
component: component_name1
},
{
path: 'childPath2',
component: component_name2
},
}
]
And thats it, now we can access this page through the route that we have created.
Warning: Make sure that when you create a new
link in sidebar ,include proper path in the
nav.service.ts
file or else the browser won't be able to
find the component at the wrong route and you will get an error of
page not found
.
Tip: You can find more information on routing in our Guide to Routing page.