Overview about Routing in Angular

Routing is a way for us to move between pages in a web application. In this tutorial, I will guide you all how we routing in Angular.

First, I will create an Angular project as an example:

Overview about Routing in Angular

Run the application, you will see the results as follows:

Overview about Routing in Angular

Now, I will split the content of the app.component.html file into two pages: a home.component.html page that has the content resemble with the current app.component.html page and the other page huongdanjava.component.html which has the contents resemble the above section including “Welcome to app!” and the Angular logo, the bottom is the words “Here is the link to Huong Dan Java” and link to my Huong Dan Java website. Details of the contents of the file will change now as follows:

Overview about Routing in Angular

home.component.html:

home.component.ts:

huongdanjava.component.html:

huongdanjava.component.ts:

At this point the contents of the app.component.html file will look like this:

The content of the AppComponent class needs to be revised as follows:

At this point, if you run the application again, you will not see anything. But if you right click, select Inspect in Google Chrome and move to the Console tab you will see the following error:

Overview about Routing in Angular

This is because we are currently defining two components with the same selector value. No problem, you can ignore this error now. Now, we will apply routing to our Angular application!

In an Angular application, the RouterModule module assumes the role of the routing object.

To use this module, we need to import it into our application, defining the routing: what URL corresponds to which component, and finally export it for our application to use.

Details, I will create a file called app-routing.module.ts in the src/app directory:

Overview about Routing in Angular

 

then define a new module using Angular’s RouterModule:

As you can see from the above, I used the Routes class to define information about the URLs that correspond to the components in our application. The “home” path will correspond to HomeComponent and the “huongdanjava” path will correspond to the HuongDanJavaComponent that it has defined.

After defining the URL information with the component, we need to pass this information to the RouterModule with the static method forRoot(). Then export the RouterModule to our application.

After we have defined the AppRoutingModule module, we need to import it into the AppModule: