Routing in Angular helps us navigate from one view to another as users perform tasks in web apps. In this guide you will learn about Angular router's primary features.
Some examples of actions users take while navigating in an app include:
Angular router can interpret a browser URL as an instruction to navigate to a client-generated view. It can pass optional parameters along to the supporting view component that help it decide what specific content to present. You can bind the router to links on a page, and it will navigate to the appropriate application view when the user clicks a link.
The Angular router is in its own library package, @angular/router. Import what you need from it as you would from any other Angular package. It is an optional service that presents a particular component view for a given URL.
File name: app.module.ts
1import { RouterModule, Routes } from '@angular/router';
Let's look at how to configure an Angular router. The following example creates five route definitions, configures the router via the RouterModule.forRoot() method, and adds the result to the
AppModule`'s imports array.
File name: app.module.ts
1const appRoutes: Routes = [
2 { path: 'company', component: CompanyComponent },
3 { path: 'employee/:id', component: EmployeeDetailComponent },
4 {
5 path: 'employees',
6 component: EmployeeListComponent,
7 data: { title: 'Employees List' }
8 },
9 { path: '',
10 redirectTo: '/employees',
11 pathMatch: 'full'
12 },
13 { path: '**', component: PageNotFoundComponent }
14];
15
16@NgModule({
17 imports: [
18 RouterModule.forRoot(
19 appRoutes,
20 { enableTracing: true }
21 )
22 ],
23 ...
24})
25export class AppModule { }
After configuring the routes, the next step is to decide how to navigate. Navigation will happen based on user actions such as clicking a hyperlink, etc.
Use the RouterLink
directive to the anchor tag for navigation, as shown below.
File name: app.module.ts
1import { Component } from '@angular/core';
2@Component({
3 selector: 'app-root',
4 styleUrls: ['./app.component.css'],
5 templateUrl: './app.component.html'
6})
7export class AppComponent {
8 title ='Employee application' ;
9}
Filename: app.component.html
1<h1>{{title}}</h1>
2<nav>
3 <a [routerLink]='["/employeedashboard"]' routerLinkActive="active">Employee Dashboard</a>
4 <a [routerLink]='["/employees"]' routerLinkActive="active">Employees</a>
5</nav>
6<router-outlet></router-outlet>
In the above example, we created hyperlinks and a routerLink
directive and specified the paths to navigate. If a user clicks on the employee dashboard, it will navigate to /employeedashboard
. routerLinkActive
applies the given CSS class to the link when it is clicked to make it look like an active link (active
is a CSS class defined in app.component.css
that changes the link color to blue in this case).
router-outlet
is the place where the output of the component associated with the given path will be displayed. For example, if a user clicks on Employees, it will navigate to /employees
, which will execute the EmployeesComponent
class as mentioned in the configuration details, and the output will be displayed in the router-outlet
class. To navigate programmatically, we can use the navigate()
method of the router
class. Inject the router
class into the component and invoke the navigate method as shown below.
1this.router.navigate([url, parameters])
Parameters passed along with a URL are called route parameters. Generate an employee dashboard component using the following CLI command.
1import { Component, OnInit } from '@angular/core';
2import { Router } from '@angular/router';
3import { Employee } from '../emploee/employee';
4import { EmployeeService } from '../employee/employee.service';
5@Component({
6 selector: 'app-employeedashboard',
7 templateUrl: './employeedashboard.component.html',
8 styleUrls: ['./employeedashboard.component.css']
9})
10export class EmployeeDashboardComponent implements OnInit {
11 employees: Employee[] = [];
12 constructor(
13 private router: Router,
14 private employeeService: EmployeeService) { }
15 ngOnInit() {
16 this.employeeService.getEmployees()
17 .subscribe(employees => this.employees = employees.slice(1, 5));
18 }
19 gotoDetail(employee: Employee) {
20 this.router.navigate(['/employeedetail', employee.id]);
21 }
22}
Import the router
class from @angular/router
module
. Inject it into the component class through a constructor
. The this.router.navigate()
method is used to navigate to a specific URL programmatically. The Navigate()
method takes two arguments: the path to navigate and tthe route parameter value to pass. Here the path will be employeedetail/<employee_id>
.
To access route parameters, use the ActivatedRoute
class. In the example below, we see that when a specific employee is clicked, it renders the EmployeeDetailComponen
t. When the employees link is clicked, it navigates to EmployeesComponent
.
Filename: employee-detail.component.ts
1import { Component, OnInit, OnDestroy } from '@angular/core';
2import { ActivatedRoute, ParamMap } from '@angular/router';
3import { switchMap } from 'rxjs/operators';
4import { Observable } from 'rxjs';
5import { Employee } from '../employee/employee';
6import { EmployeeService } from '../employee/employee.service';
7@Component({
8 selector: 'app-employee-detail',
9 templateUrl: './employee-detail.component.html',
10 styleUrls: ['./employee-detail.component.css']
11})
12export class EmployeeDetailComponent implements OnInit, OnDestroy {
13 employee: Employee;
14 error: any;
15 sub: any;
16 constructor(private employeeService: EmployeeService, private route: ActivatedRoute) { }
17 ngOnInit() {
18
19 this.sub = this.route.paramMap.pipe(switchMap((params: ParamMap) =>
20 this.employeeService.getEmployee(+params.get('id')))).subscribe(employee => this.employee = employee);
21 }
22 ngOnDestroy() {
23 this.sub.unsubscribe();
24 }
25 goBack() {
26 window.history.back();
27 }
28}
Import the ActivatedRoute
class to access route parameters
. Inject the ActivatedRoute
class into the component class through a constructor
. The ActivatedRoute
class has a paramMap
observable method that holds the route parameters. It has the switchMap()
method to process the route parameters. ParamMap
has a get()
method to fetch a specific parameter value
.
In this guide, we have explored how to use routing in Angular. We have also seen how to use routing in an app using routerlink
and routing parameters.
You can learn more about Angular in my guide Using the Async Pipe in Angular.