Angular Dynamic Page Title Based On Route

Introduction

 
We will learn how to set the dynamic page title in am Angular application based on the change of route. We will set the different title for different route.
 
Prerequisites
 
Basic knowledge of Angular components/modules and routes . I will demonstrate how to set dynamic title of page. Before proceeding, you must have basic knowledge of Angular. I am assuming that you have already created an Angular app. Here, I'll show how to add the functionality of dynamic title in your existing app.
 
We will use TitleService to implemet dynamic title functionality.
 

TitleService

 
This is an inbuilt service in `@angular/platform-browser` package. It is a simple class which provides an API for setting and getting the title of HTML page. It provides two methods to get and set the title of HTML page,
  1. getTitle() : string : Returns the title of cuurent HTML page in string format.
  2. setTitle( newTitleName : string ) — Sets the title of the current HTML page.
Step 1
 
Create three components named as HomeComponent , DashboardComponent and Dashboard2Component as shown in image below. We will use these components to set the different titles.
 
Angular Dynamic Page Title Based On Route
 
Step 2 - Import Title Service
 
Open the app.module.ts file and import the Title from @angular/platform-browser module as shown below.
  1. import { BrowserModule , Title} from '@angular/platform-browser';  
and register the service in provider metdata as shown below:
  1. providers: [Title]  
Step 3
 
Open app.routing.module.ts file or if not exists create new file. We will add the route and there respective title in this file. Add the route as shown below in file.
  1. import { NgModule, Component } from '@angular/core';  
  2. import { Routes, RouterModule } from '@angular/router';  
  3.   
  4. import { DashboardComponent } from './dashboard/dashboard.component';  
  5. import { Dashboard2Component } from './dashboard2/dashboard2.component';  
  6. import { HomeComponent } from './home/home.component';  
  7.   
  8. const routes: Routes = [  
  9.   {  
  10.     path : 'dash',  
  11.     component : DashboardComponent,  
  12.     data : {  
  13.         title: 'App Dashboard '  
  14.     }  
  15.   },  
  16.   {  
  17.     path : 'dashboard',  
  18.     component : Dashboard2Component,  
  19.     data : {  
  20.       title: 'Dashboard 2'  
  21.   }  
  22.   },  
  23.   {  
  24.     path : 'home',  
  25.     component : HomeComponent,  
  26.     data : {  
  27.       title: 'Home Page'  
  28.   }  
  29.   },  
  30.   {  
  31.     path : '',  
  32.     component : HomeComponent,  
  33.     data : {  
  34.       title: 'Home Page'  
  35.   }  
  36.   }  
  37. ];  
  38.   
  39. @NgModule({  
  40.   imports: [RouterModule.forRoot(routes)],  
  41.   exports: [RouterModule]  
  42. })  
  43. export class AppRoutingModule { }  
Here we have added the routes for all our three component created in first step with there respective title given in data attribute. Now we have to import this AppRoutingModule in App module.
 
Final app.module.ts file will look like as below. 
  1. import { BrowserModule , Title} from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3.   
  4. import { AppRoutingModule } from './app-routing.module';  
  5. import { AppComponent } from './app.component';  
  6.   
  7. import { DashboardComponent } from './dashboard/dashboard.component';  
  8. import { Dashboard2Component } from './dashboard2/dashboard2.component';  
  9. import { HomeComponent } from './home/home.component';  
  10.   
  11. @NgModule({  
  12.   declarations: [  
  13.     AppComponent,  
  14.     DashboardComponent,  
  15.     Dashboard2Component,  
  16.     HomeComponent  
  17.   ],  
  18.   imports: [  
  19.     BrowserModule,  
  20.     AppRoutingModule  
  21.   ],  
  22.   providers: [Title],  
  23.   bootstrap: [AppComponent]  
  24. })  
  25. export class AppModule { }  
Step 4
 
To change the title on route change we have to subscribe the route change event. We will subscribe to this event in app.component.ts file because this component gets loaded when the app starts and it lives as long as the app lives . Hence we will subscribe to route change event in app.component.ts file.
 
Open the app.component.ts file and add the code as given below.
  1. import { Component , OnInit } from '@angular/core';  
  2. import { Title } from '@angular/platform-browser';  
  3. import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';  
  4. import { filter } from 'rxjs/operators';  
  5.   
  6. @Component({  
  7.   selector: 'app-root',  
  8.   templateUrl: './app.component.html',  
  9.   styleUrls: ['./app.component.scss']  
  10. })  
  11. export class AppComponent implements OnInit  {  
  12.     
  13.   constructor(private router: Router,  
  14.               private activatedRoute: ActivatedRoute,  
  15.               private titleService: Title) {  
  16.   
  17.   }  
  18.   
  19.   ngOnInit() {  
  20.     this.router.events.pipe(  
  21.         filter(event => event instanceof NavigationEnd),  
  22.       ).subscribe(() => {  
  23.         const rt = this.getChild(this.activatedRoute);  
  24.         rt.data.subscribe(data => {  
  25.           console.log(data);  
  26.           this.titleService.setTitle(data.title)});  
  27.       });  
  28.   }  
  29.   
  30.   getChild(activatedRoute: ActivatedRoute) {  
  31.     if (activatedRoute.firstChild) {  
  32.       return this.getChild(activatedRoute.firstChild);  
  33.     } else {  
  34.       return activatedRoute;  
  35.     }  
  36.   
  37.   }  
  38.   
  39. }  
Here first we have injected the Router, ActivatedRoute & Title services in our constructor. And in ngOnInit we subscribed to router event. There are so many events in router event such as NavigationStart, NavigationEnd etc., and that's why we have given the filter to listen only when NavigationEnd event occurs. We have used ActivatedRoute to get the bottom most current activated route. At last we have used setTitle() method of title service to set the title based on value given in data attribute in route file.
 
Launch the application and navigate to different route and you will be able to see the different titles of pages as given in route file.
 
Angular Dynamic Page Title Based On Route
 
As you can see in the above image we can see a different title for both routes. 
 

Conclusion

 
We have used TitleService to set the dynamic titles of pages based on current route. We have subscribed to router event to know when route of application changes and based on route change we have set the title of page using setTitle() method of TitleService.
 
Thank you for reading this article!!! Please provide your feedback and question in comment section to make this article useful.