To implement the navigation within the single page of your Angular application, use the 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 13 Router
Angular Router is a built-in robust JavaScript router maintained by the Angular core team. We don’t need to separate, 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 navigation between them.
Angular Router Navigate
To navigate different routes, use the Angular router as it provides methods to navigate different routes using routerLink. To navigate from one route to another, we need two Angular components. Each component contains a specific view.
Navigation Directive
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. Therefore, we need to map a specific component to the path /home.
In Angular 13, there is an app-routing.module.ts module file. In that file, you can define the routes array that contains objects. We can define a different path and component in those objects, and angular will map the path to that component accordingly. So it will render specific components to a particular path.
Angular 13 routerLink
If you don’t know how to update to Angular 13, then check out the updated Angular CLI version guide.
To create a new angular 13 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.
- HomeComponent
- 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 containing 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.
- path
- component
You can map the different routes to different components here and, finally, register all the routes using RouterModule.forRoot() function.
Angular 13 Router-outlet
The Router-Outlet is the directive that the angular router library provides, 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, enabling 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 a sibling of the Router outlet.
Let’s write <router-outlet> directive inside the app.component.html file in our example.
<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.
- http://localhost:4200/
- http://localhost:4200/home
- 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 that 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.
Navigating Programmatically via Angular Router
To navigate programmatically in Angular, use the Router service we inject into our component.
The Angular 13 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.
- navigate()
- navigateByUrl()
They can be helpful 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 navigates () 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.
In our example, let’s see how to use the router navigate() method.
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. You can programmatically navigate to a specific route in Angular based on your custom condition.
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. However, you will be redirected to /dashboard route after a second.
Conclusion
Navigating routes in single-page applications are the most common programming implementation. In this tutorial, we have seen how to navigate different routes using routerLink, a standard way, and router.navigate() or router.navigateByUrl() function, which is programmatically in Angular.
That’s it for this Angular 13 router navigate guide.