Routing means navigating from one page to another page in an application. In this blog, we will create routes, child routes in an Angular app to demonstrate the concept of routing in Angular.
We will see Routing, Child Routing and Params which are main concept in Angular routing and same will help in building single page application.
Routing in Angular
While creating a new Angular project through CLI, it ask ‘Would you like to add Angular routing? (y/N)’
Once you select yes, it creates a app-routing.module.ts file in src-> app folder.
This file import NgModule, Routes, RouterModule.
Read:- Angular Interview Questions
Router-Outlet, Routes, path are main component in Angular Routing.
We have to define all the routes in Routes. Routes is an array of route configuration.
To define all the routes in app-routing module first import all the component.
Now add values to Routes array as shown below.
Now build your project by using ng serve command and open your application in a browser.
Try to navigate /page1, /page2 and /page3, we will see that corresponding html content is loading in browser.
What is Child Routing in Angular?
Child Routing is the part of routing in Angular. Child Routing is useful in case we have want to create submenu.
For eg – A product menu can have multiple child menu such as Product Type1, Product Type2 …..
In our case, we will create a new component called ‘mainpage’ and there will be 3 submenu page1, page2, page3
In this scenario we have to modify Routes array in app-routing module file.
Now, we have to modify our mainpage.component.html file (i.e. Parent html page of child menu)
Add child links and <router-outlet> tag.
We can access /main/page1, /main/page2 and /main/page3 respectively to access page1, page2 and page3.
To access parameters in URL. It is similar to accessing query string value from a URL.
For eg – [http://][localhost]:[4200/details/<prdid>]
And then, we will access the value of prdid which will be dynamic.
I have created a DetailsComponent to display the details of the product.
To access Params from URL in Angular first import ActivatedRoute in DetailsComponent file
And add below code to DetailsComponent class file.
Note- prdid is the same variable which we will define in route.
Now, we will define the route for Params
Now open DetailsComponent html file to access the Param available in URL
Note – productId used in Component HTML file is same variable used in DetailsComponent class file.
Hope you like this blog.
Please share this blog on social media and give your feedback in comment box below.
You may like other blogs –