In this tutorial, we will take look at routing in Angular 5. Routing is the basic part of any application. Whenever you need multiple pages in your application, then you must be familiar with the concept of routing. Because routing means navigating between pages.
Previous Tutorial of Angular 5 Series
- How to install angular 5 using VS Code.
- Components in Angular 5.
- What is Module in Angular
- Data Binding in Angular 5.
How to implement Routing in Angular 5?
Let’s see how to implement routing in angular 5 Application.
Note: – In this tutorial, we will not create a new project. We will use that project which we have created in one of the previous tutorials. If you want to learn how to create a new project, then click here.
As you know we have two components in our project one is App component and the other one is Home Component. And we want to navigate between home component (home component page which is the child) and app component (app component main page which is the parent).
So, first of all, we need to import router module in our parent component. Go to folder structure => open app.module.ts file from under the app folder. And then add the router module as you see below.
Line # 3: Router Module is imported here in this line.
Line # 17: Router module is added in imports as you see in this line.
So, RouterModule refers to the forRoot which takes an input as an Array. Now, it takes two objects one is the “path” and the other one is “component“. The Path is the name of the router and the component is the name of the class which we have created in home.component.ts.
Now, we need to add the router details of app.component.html as you see below code.
Line # 4: As you see we have added RouterLink, which is the path that referred from app.module.ts, in the anchor link tag.
Line # 7: This router outlet tag is used, when a user clicks on the “Home” link, then the content of the home page should display.
Now, see the below code for home.component.html file, which we have added in previous tutorials.
So, when you run your project, then the main page will be displayed as you see below.
So, when a user clicks the Home link then the below output will be displayed.
Moreover, when you click on the home link, then you will see the URL like this http://localhost:4200/home . The home part gets appended to the original URL. And this home part of URL is the path which is given in the app.module.ts file and the router link in the app.component.html file.