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,
- getTitle() : string : Returns the title of cuurent HTML page in string format.
- 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.
Step 2 - Import Title Service
Open the app.module.ts file and import the Title from @angular/platform-browser module as shown below.
- import { BrowserModule , Title} from '@angular/platform-browser';
and register the service in provider metdata as shown below:
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.
- import { NgModule, Component } from '@angular/core';
- import { Routes, RouterModule } from '@angular/router';
-
- import { DashboardComponent } from './dashboard/dashboard.component';
- import { Dashboard2Component } from './dashboard2/dashboard2.component';
- import { HomeComponent } from './home/home.component';
-
- const routes: Routes = [
- {
- path : 'dash',
- component : DashboardComponent,
- data : {
- title: 'App Dashboard '
- }
- },
- {
- path : 'dashboard',
- component : Dashboard2Component,
- data : {
- title: 'Dashboard 2'
- }
- },
- {
- path : 'home',
- component : HomeComponent,
- data : {
- title: 'Home Page'
- }
- },
- {
- path : '',
- component : HomeComponent,
- data : {
- title: 'Home Page'
- }
- }
- ];
-
- @NgModule({
- imports: [RouterModule.forRoot(routes)],
- exports: [RouterModule]
- })
- 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.
- import { BrowserModule , Title} from '@angular/platform-browser';
- import { NgModule } from '@angular/core';
-
- import { AppRoutingModule } from './app-routing.module';
- import { AppComponent } from './app.component';
-
- import { DashboardComponent } from './dashboard/dashboard.component';
- import { Dashboard2Component } from './dashboard2/dashboard2.component';
- import { HomeComponent } from './home/home.component';
-
- @NgModule({
- declarations: [
- AppComponent,
- DashboardComponent,
- Dashboard2Component,
- HomeComponent
- ],
- imports: [
- BrowserModule,
- AppRoutingModule
- ],
- providers: [Title],
- bootstrap: [AppComponent]
- })
- 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.
- import { Component , OnInit } from '@angular/core';
- import { Title } from '@angular/platform-browser';
- import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
- import { filter } from 'rxjs/operators';
-
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.scss']
- })
- export class AppComponent implements OnInit {
-
- constructor(private router: Router,
- private activatedRoute: ActivatedRoute,
- private titleService: Title) {
-
- }
-
- ngOnInit() {
- this.router.events.pipe(
- filter(event => event instanceof NavigationEnd),
- ).subscribe(() => {
- const rt = this.getChild(this.activatedRoute);
- rt.data.subscribe(data => {
- console.log(data);
- this.titleService.setTitle(data.title)});
- });
- }
-
- getChild(activatedRoute: ActivatedRoute) {
- if (activatedRoute.firstChild) {
- return this.getChild(activatedRoute.firstChild);
- } else {
- return activatedRoute;
- }
-
- }
-
- }
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.
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.