Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Navigating to Routes from Code in Angular

Feb 23, 2020 • 8 Minute Read


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.

      ng g c first --skipTests=true
ng g c second --skipTests=true
ng 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.

      import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SecondComponent } from './second/second.component';
import { FirstComponent } from './first/first.component';
import { FirstChildComponent } from './first-child/first-child.component';

const routes: Routes = [
    path: 'first',
    component: FirstComponent,
    children: [
        path: 'first-child',
        component: FirstChildComponent
    path: 'second',
    component: SecondComponent
    path: "",
    redirectTo: '/first',
    pathMatch: 'full'

  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
export 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.

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.

    <button type="button" class="btn" (click)="navigateToFirst()">First</button>
    <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.

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

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
export class AppComponent {

  constructor(private _router: Router) { }

  navigateToFirst() {
  navigateToSecond() {


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.

    color: white;
    background-color: blue;
    border: none;
    padding: .5em 2em;
    border-radius: 2em;
    box-shadow: 0 0 2px 2px;
    font-size: 18px;
    margin-left: 5px;
    margin-right: 5px;
    outline: none;
        background-color: gray;
        cursor: pointer;

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.

      <p>first works!</p>
<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.

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

  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ['./first.component.scss']
export class FirstComponent implements OnInit {

    private _router: Router,
    private _activatedRoute:ActivatedRoute
    ) { }

  navigateToFirstChild() {


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.