Author avatar

Gaurav Singhal

Navigating to Routes from Code in Angular

Gaurav Singhal

  • Feb 23, 2020
  • 8 Min read
  • Feb 23, 2020
  • 8 Min read
Languages Frameworks and Tools


Hello friends! As you know, Angular is a single-page application, and it doesn't have multipage HTML pages to create different routes, so we require a client-side routing solution. The Angular Router helps us to create client-side routing in a few simple steps, and then we can render using routerLink. Today, I will walk you through different options to navigate from components to various other components using code so you can navigate the user dynamically using different conditions.

What We Will Cover

  • The need for dynamic routing
  • Making routes with different components
  • Navigating between components using routes from code

The Need for Dynamic Routing

Let's take a real-life and straightforward example. Suppose you have multiple roles in your application, and depending on the role, you have to decide whether or not users are authorized to access your application. If they have the authority, you'll navigate them to the home page of the application; otherwise, you'll take them to a different page, preferably with a 403 status code.

In this scenario, you will need to decide the route in one hit at the time of form submission on the login page. So what are you going to do?

Here dynamic routing comes into the picture. First, you will check the condition, and depending on that condition, you will dynamically decide the routes where a user will be sent.

Let's get started with the next section by making routes in app-routing.module.ts.

Making Routes with Different Components

Now we're going to make some of the components that will help us to understand Angular Router more clearly. I am going to create three components: FirstComponent, SecondComponent, and FirstChildComponent, respectively. FirstChildComponent will be used in the FirstComponent as a child component.

The following commands will create the components.

1ng g c first --skipTests=true
2ng g c second --skipTests=true
3ng g c first-child --skipTests=true

We have successfully created the components; now, we will map it with different URI. After successfully configuring app-routing.module.ts, it will look as follows.

1import { NgModule } from '@angular/core';
2import { Routes, RouterModule } from '@angular/router';
3import { SecondComponent } from './second/second.component';
4import { FirstComponent } from './first/first.component';
5import { FirstChildComponent } from './first-child/first-child.component';
7const routes: Routes = [
8  {
9    path: 'first',
10    component: FirstComponent,
11    children: [
12      {
13        path: 'first-child',
14        component: FirstChildComponent
15      }
16    ]
17  },
18  {
19    path: 'second',
20    component: SecondComponent
21  },
22  {
23    path: "",
24    redirectTo: '/first',
25    pathMatch: 'full'
26  }
30  imports: [RouterModule.forRoot(routes)],
31  exports: [RouterModule]
33export class AppRoutingModule { }

In the routes file, we have created two main routes, /first and /second, and a default route that will redirect to /first. Mainly, it is for redirecting the user to the home page initially. We have also created children routing to explain the dynamic navigation for the parent-child relationship.

It's time to write the chunks of code for navigating between the component using routes.

Navigate Between the Components using Routes from Code

I am not going to write a condition for now; rather, I will make a couple of buttons in app.component.html. On click, it will navigate to different components.

2    <button type="button" class="btn" (click)="navigateToFirst()">First</button>
3    <button type="button" class="btn" (click)="navigateToSecond()">Second</button>

As you can see, we have successfully added two buttons in app.component.html, and on click events methods are going to call navigateToFirst() and navigateToSecond(), respectively. These methods will call the navigate() method of the Router class to navigate to another view.

So let's add these functions to our app.component.ts file.

1import { Component } from '@angular/core';
2import { Router } from '@angular/router';
5  selector: 'app-root',
6  templateUrl: './app.component.html',
7  styleUrls: ['./app.component.scss']
9export class AppComponent {
11  constructor(private _router: Router) { }
13  navigateToFirst() {
14    this._router.navigate(['first'])
15  }
16  navigateToSecond() {
17    this.router.navigateByUrl('/second')
18  }

Here we have injected the router class in the constructor that enables us to navigate from one view to another. It has two methods, navigate and navigateByUrl, that navigate the routes. They are similar; the only difference is that the navigate method takes an array that joins together and works as the URL, and the navigateByUrl method takes an absolute path.

For example, if we have to navigate to /students/1, we can navigate to this URL in two ways.

  1. this._router.navigate('students',1)
  2. this._router.navigateByUrl('/students/1')

On button click, you can add some condition to navigate the user on different conditions.

Now I am going to apply some of the CSS to beautify our application. I'll put it in the style.scss file.

2    color: white;
3    background-color: blue;
4    border: none;
5    padding: .5em 2em;
6    border-radius: 2em;
7    box-shadow: 0 0 2px 2px;
8    font-size: 18px;
9    margin-left: 5px;
10    margin-right: 5px;
11    outline: none;
12    &:hover{
13        background-color: gray;
14        cursor: pointer;
15    }

I have used SCSS here. If you're not familiar with it, you can read about it here. You can use CSS, too, if you're not comfortable with SCSS.

Our output will look like this.

Now It's time to bring the FirstChildComponent into the picture. We'll make a button like app.component.html in first.component.html.

1<p>first works!</p>
2<button type="button" class="btn" (click)="navigateToFirstChild()">First</button>

After making changes in first.component.ts, it will look like the above snippet in which we have a button that will call a function on click event, which will then navigate it and show the child view.

Now we're going to make a function in first.component.ts to navigate to FirstChildComponent.

1import { Component, OnInit } from '@angular/core';
2import { Router, ActivatedRoute } from '@angular/router';
5  selector: 'app-first',
6  templateUrl: './first.component.html',
7  styleUrls: ['./first.component.scss']
9export class FirstComponent implements OnInit {
11  constructor(
12    private _router: Router,
13    private _activatedRoute:ActivatedRoute
14    ) { }
16  navigateToFirstChild() {
17    this._router.navigate(["first-child"],{relativeTo:this._activatedRoute})
18  }

Note: In the navigate() method, I have passed an extra parameter. It is a kind of object known as NavigateExtras. We have used relativeTo of NavigateExtras, and in the value, we have given the instance of ActivatedRoute. So you don't need to provide the whole URL in the array, and it will automatically extend the current parameter after the existing URL.

Finally, our output looks like this.


I hope you have enjoyed this guide. There are multiple situations in which you might need dynamic routing. I have explained some of them in the above example. I tried to cover all aspects of dynamic navigation. To learn to use dynamic routing more effectively, read more about it here.