Routing in Angular

Routing in Angular Application

In this article, I am going to discuss Routing in Angular Application with Examples. Please read our previous article, where we discussed how to create Angular Custom Pipes in Detail. At the end of this article, you will understand the following pointers in detail.

  1. What is Routing in Angular?
  2. Why Routing in Angular Application?
  3. Understanding Angular Routing with an example.
  4. Configuring Routes in Angular Application.
  5. What is Router-outlet and routerLink?
  6. What is Angular Router?
What is Routing in Angular?

The Angular Routing is a mechanism which is used for navigating between pages and displaying appropriate component or pages on the browser.

In other words we can say that the Routing in Angular Application helps us to navigate across the application from one one view to another view. It also allows us to maintain the state, implement modules, and then loads the modules based on the roles of the user. If this is not clear at the moment, then don’t worry, we will try to understand each and everything with examples.

Why Routing in Angular Application?

We access our application through one URL such as http://localhost:4200 and our application is not aware of any other URLs such as http://localhost:4200/Login

Most web applications need to support different URLs to navigate different pages of the application. This is where angular routing comes into picture.

Understanding Angular Routing with an example:

Let us understand the Routing in Angular Application with an example. We want to create a page as shown below.

Routing in Angular Application

When the user click on the student link, we need to display the following.

What is Routing in Angular?

And when the user click on the student details link, we need to display the following.

Why Routing in Angular Application?

Let us see how to implemeny this using Angular Routing. Here, we need to create two components i.e. student and studentdetails component.

Creating Student Component:

Open terminal and type ng g c student and press enter as shown in the below image.

Creating Student Component:

Once you press enter it will create four files within the student folder which you can find within the src/app folder as shown in the below image.

Creating Student Component using Angular CLI

Modifying the student.component.html file:

Open student.component.html file and then copy and paste the following code in it.

<p>You are in the student.component.html</p>

Creating Student Details Component:

Open terminal and type ng g c studentdetail and press enter as shown in the below image.

Creating Student Details Component:

Once you press enter it will create four files within the studentdetail folder which you can find inside the src/app folder as shown in the below image.

Creating Student Details Component using Angular CLI

Modifying studentdetail.component.html file:

Open studentdetail.component.html file and then copy and paste the following code in it.

<p>You are in studentdetail.component.html</p>

Adding Routing in Angular:

When you are creating an angular 9 application, at the time of creation it is asking whether you want to add angular routing to your project or not. If you select yes, then it automatically add the routing model in your project. If you select no then you need to add it manually. You can use the below CLI code to generate the router in Angular Application.

ng generate module app-routing –flat –module=app

Here –flat puts the file in src/app folder instead of its own folder and –module=app tells the CLI to register it in the imports array of the AppModule.

Configuring Routes in Angular Application:

Once you created the routing module, then you need to configure the path and their respective component in the AppRoutingModule as shown in the below image. As you can see, here we have created two paths i.e. studentLink and studentdetailsLink (you need to use the path properties to set the path. You can give any meaningful name here) and also set the respective components using the component property (Here you need to provide the component class name).

Configuring Routes in Angular Application

So, open app-routing.module.ts file and then copy and paste the following code in it.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { StudentComponent } from './student/student.component';
import { StudentdetailComponent } from './studentdetail/studentdetail.component';

const routes: Routes = [
  {
    path:'studentLink', component:StudentComponent
  },
  {
    path:'studentdetailsLink', component: StudentdetailComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Note: While generating the link you need to use the string studentLink and studentdetailsLink. Let us see how to use these routing path to generate link and navigates.

Generating to Links:

In order to generate links, open app.component.html file and then copy and paste the following code in it.

<h2>Angular Routing Example</h2>

<a [routerLink] = "['/studentLink']" >Student</a> <br/>
<a [routerLink] = "['/studentdetailsLink']" >student details</a>

<div>
    <router-outlet></router-outlet>
</div>

With the above changes in place, now run the application and you should get the output as expected. From the above HTML Code, we need to understand two important concepts i.e. routerLink and router-outlet

Router-outlet:

The Router Outlet is a dynamic component that the router uses to display views based on router navigation. In our example, whenever the user click on the Student Link, then it will display student component view in the router-outlet div. So, the role of <router-outlet> is to mark where the router displays the view. This is the location where angular will insert the component.

The <router-outlet> tells the router where to display routed view. The RouterOutlet is one of the router directives that become available to the AppComponent because AppModule imports AppRoutingModule which exported RouterModule.

Router Link:

With the help of routerLink directive, you can link to routes of your application right from the HTML Template. You just need to add the directive to an HTML Element. When the user clicks on that element, angular navigates to that specified location.

The routerLink is the selector for the RouterLink directive that turns user clicks into router navigations. You can assign a string to the Router link. This directive generates the link based on the route path.

Router Link: Client side

The syntax is given below. As you can see within the anchor tag we have routerLink and we have specified the studentLink as its path. If you remember we have set this studentLink path in the routing module and it is pointing to the Student Component. So, when the Student List is clicked, then the student component is going to be load on the router-outlet directive.

Router Link: Client side

Router Link: Server side

Sometimes it is also required to set the route dynamically based on some condition and that can be done at server side. For your application to work with server side rendering, the element hosting directive has to be a link (anchor) element.

It is also possible to navigate to a route from code. To do so, we need angular router and this need to be done in your typescript file. The syntax is given below.

Router Link: Server side

Once we have the router, then the navigation is quite simple. Just call the navigate function or Router. This function takes an array. The first element of the array defines the route we want to navigate. The second is optional and allows us to pass a route parameter. The syntax is given below.

Understanding Angular Routing with an example

Let us see an example to understand this:

First modify the app.component.ts file as shown below.

import { Component} from '@angular/core';
import {Router} from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    constructor(private router : Router){}
    GetStudent()
    {
        this.router.navigate(['/studentLink']);
    }

    GetStudentDetails()
    {
        this.router.navigate(['/studentdetailsLink']);
    }
}

Then modify app.component.html file as shown below.

<h2>Angular Routing Example</h2>

<button (click)="GetStudent()">Student</button>
<button (click)="GetStudentDetails()">GetStudentDetails</button>

<div>
    <router-outlet></router-outlet>
</div>

With the above changes in place, now run the application and it should works as expected.

What is Angular Router?

The Angular Router is an official Routing Library managed by the Angular Core Team. Its a JavaScript router implementation that’s designed to work with Angular and is packaged as @angular/router

The Angular Router will take cares of the duties of a JavaScript router. It activates all required Angular Components to compose a page when a user navigates to a certain URL. It lets user navigate from one page to another without page reload.

It updates the browsers history so that the user can use the back and forward buttons when navigating back and forth between pages.

In the next article, I am going to discuss Redirecting Routes in Angular Application in detail. Here, In this article, I try to explain the basics of Routing in Angular Application. I hope you enjoy this article.

Leave a Reply

Your email address will not be published. Required fields are marked *