AppDividend
Latest Code Tutorials

Beginners Guide to Angular Router Navigate with Example

0

To implement the navigation within the single page of your Angular application, use the Angular Router. To handle the navigation from one view to the next, use the Angular router. The router enables navigation by interpreting a browser URL as an instruction to change the view.

Introducing Angular 10 Router

Angular Router is an inbuilt robust JavaScript router that is maintained by the Angular core team. We don’t need to separately, and it will come out of the box.

The router provides a comprehensive routing library with the opportunity to have multiple router outlets, different path matching strategies, easy access to route parameters, and route guards to shield components from unauthorized access.

The Angular router is the fundamental block of the Angular platform. It enables developers to build Single Page Applications(SPAs) with multiple views and provide navigation between these views.

Angular Router Navigate

To navigate different routes, Angular router provides methods that can navigate different routes using routerLink and programmatically. To navigate from one route to another, we at least need two Angular components. Each component contains a specific view.

Angular Router supports the routerLink directive to create navigation links. The navigation directive takes the path associated with the component to navigate to.

Syntax

<a [routerLink]="'/home'">Home</a>

In the above code, ‘/home’ is the path. We need to map a specific component to the path /home. 

In Angular 10, there is an app-routing.module.ts module file. In that file, you can define the routes array that contains objects. In those objects, we can define a different path and component, and angular will map the path to that component accordingly. So it will render specific components to a particular path.

Angular 10 routerLink Example

If you don’t know how to update to Angular 10, then check out the update Angular CLI version 10 guide.

To create a new angular 10 project, type the following command.

ng new angularguard

While creating a new project, please enable the routing. So it will create the app-routing.module.ts file.

Now, create two following components.

  1. HomeComponent
  2. DashboardComponent

To create a component in Angular, you have to type the following command.

ng g c home --skipTests=true
ng g c dashboard --skipTests=true

After creating a component, we will define the routes array that contains different objects.

So, write the following code inside the app-routing.module.ts file.

// app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { DashboardComponent } from './dashboard/dashboard.component';

const routes: Routes = [
  { path: 'home', component: HomeComponent},
  { path: 'dashboard', component: DashboardComponent }
];

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

You can see that we have defined the routes array that contains two objects. The keys to the objects are the following.

  1. path
  2. component

You can map the different routes to different components here and, finally, register all the routes using RouterModule.forRoot() function.

Angular 10 Router-outlet

The Router-Outlet is the directive that’s provided by the angular router library where the router adds the component that gets matched based on the current browser’s URL.

You can add multiple router outlets in your application as per your requirements, which enables you to implement advanced routing scenarios. See the Router-outlet syntax.

<router-outlet></router-outlet>

Any component that gets matched by the Router will render it as a sibling of the Router outlet.

In our example, let’s write <router-outlet> directive inside the app.component.html file.

<h3>Welcome to router navigate</h3>
<router-outlet></router-outlet>

Now, you have three URLs to render. One is the root, and the other two, we have defined in the routes array. You can access the components by the following URLs.

  1. http://localhost:4200/
  2. http://localhost:4200/home
  3. http://localhost:4200/dashboard

Right now, there is no navigation bar. So let’s add bootstrap navigation by installing bootstrap 4.

npm install bootstrap --save

Register the bootstrap.min.css file inside the angular.json file.

"styles": [
       "src/styles.css",
       "./node_modules/bootstrap/dist/css/bootstrap.min.css"
],

Now, we will add the navigation bar inside the app.component.html file.

<nav class="navbar navbar-light navbar-expand-lg" style="background-color: #e3f2fd;">
  <div class="container">
    <a class="navbar-brand">AppDividend</a>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto">
          <li class="nav-item">
            <a class="nav-link">
            Home
            </a>
          </li>
          <li class="nav-item">
            <a class="nav-link">
            Dashboard
            </a>
          </li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <router-outlet></router-outlet>
</div>

You can see that we have not written a routerLink directive inside the anchor tag.

To navigate from one route to another route, we have to put the routerLink directive.

The routerLink directive takes a route path which we have already defined inside the routes array.

Let’s add the directive.

<!-- app.component.html -->

<nav class="navbar navbar-light navbar-expand-lg" style="background-color: #e3f2fd;">
  <div class="container">
    <a routerLink="/" class="navbar-brand" routerLinkActive="active" >AppDividend</a>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto">
        <ng-container>
          <li class="nav-item">
            <a routerLink = "home" class="nav-link">
            Home
            </a>
          </li>
          <li class="nav-item">
            <a routerLink = "dashboard" class="nav-link">
            Dashboard
            </a>
          </li>
         </ng-container>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <router-outlet></router-outlet>
</div>

Save the file, and now you can navigate easily from one route to another route.

Navigating Programmatically via Angular Router

To navigate programmatically in Angular, use the Router service that we inject into our component.

The Angular 10 Router service provides two methods that you can use to navigate from one component to other components in your component class instead of using the RouterLink directive in the template, as we have just seen.

The two methods are the following.

  1. navigate()
  2. navigateByUrl()  

They can be useful in multiple programming scenarios where you need to trigger the navigation via code. Both functions return a promise that resolves to either true or false.

The navigateByUrl() method takes a string as a parameter.

The navigate() method takes an array of URL segments.

Angular router navigate() method.

The router navigate() method accepts the same one-item link parameters array that you can bind to the [routerLink] directive.

To navigate programmatically in angular, use the router navigate() method.

Let’s see how to use the router navigate() method in our example.

Write the following code inside the home.component.ts file.

// home.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  constructor(private router: Router) { }

  ngOnInit(): void {
    setTimeout(() => {
      this.router.navigate(['/dashboard']);
    }, 1000);
  }
}

In this example, we programmatically navigate the route from /home to /dashboard.

The ngOnInit() function automatically gets called when the component is initialized, and then after waiting for 1 second, the router programmatically navigates to the /dashboard route using the router.navigate() function.

So, go to the home route using the navbar, and then after a second, you will navigate to the /dashboard route. Based on your custom condition, you can programmatically navigate to a specific route in Angular.

Angular router.navigateByUrl()

The router.navigateUrl() function takes redirect URL.

In our scenario, we can use the router.navigateByUrl() function instead of router.navigate() function.

Write the following code inside the home.component.ts file.

// home.component.ts

ngOnInit(): void {
    setTimeout(() => {
      this.router.navigateByUrl('/dashboard');
    }, 1000);
  }

Save the file, and you will get the same output. After a second, you will be redirected to /dashboard route.

Conclusion

Navigating routes in single page application is the most common programming implementation. In this tutorial, we have seen how to navigate different routes using routerLink, which is a standard way and router.navigate() or router.navigateByUrl() function which is programmatically in Angular.

That’s it for this Angular 10 router navigate guide.

See also

Angular 10 Tutorial

Angular 10 Features

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.