Dynamic Page Title Based On Route In Angular 9

In this article, we will learn how to implement a dynamic page title based on the route in Angular 9.

Set up the title in each component is a tedious task. A developer may miss some of the components. The simpler solution is to define the title along with the routes and use it to update the title.

Prerequisites:

  • Basic knowledge of Angular
  • Code editor like Visual Studio Code

Create a new Angular project by typing the following command in the VSCode terminal.

ng new dynamic-title

Now, open the newly created project and execute the commands given below. It will create two components home and about.

ng g c home
ng g c about

To implement dynamic title functionality we will use Title service.

Angular bridges the gap by providing Title service as part of the browser platform in @angular/platform-browser package. The Title service is a simple class that provides an API for getting and setting the current HTML page title. It provides two methods:

  • getTitle() : Gets the title of the current HTML page in string format.
  • setTitle(newTitle : string) : Sets the title of the current HTML page.

Open the app.module.ts file and add the code in it.

import { BrowserModule, Title } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    AboutComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [
    Title
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Open the app-routing.module.ts file and add the code in it.

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

const routes: Routes = [
  {
    path: 'home',
    component: HomeComponent,
    data: {
      title: 'Home'
    }
  },
  {
    path: 'about',
    component: AboutComponent,
    data: {
      title: 'About'
    }
  },
  {
    path: '',
    component: HomeComponent,
    data: {
      title: 'Home'
    }
  }
];

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

Open the app.component.html file and add the code in it.

<button routerLink="/home">Home</button>
<button routerLink="/about">About</button>

<router-outlet></router-outlet>

We have to subscribe to the route change event, to change the title on route change. The app.component.ts is the topmost component in our app. It loads when the app starts and it lives as long as the app lives.

Open the app.component.ts file and add the code in it.

import { Component } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { filter } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(private router: Router, private activatedRoute: ActivatedRoute, private titleService: Title) { }

  ngOnInit() {
    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd),
    ).subscribe(() => {
      const childRoute = this.getChild(this.activatedRoute);
      childRoute.data.subscribe(data => {
        this.titleService.setTitle(data.title)
      });
    });
  }

  getChild(activatedRoute: ActivatedRoute) {
    if (activatedRoute.firstChild) {
      return this.getChild(activatedRoute.firstChild);
    }
    else {
      return activatedRoute;
    }

  }

}

Output:

 

Please give your valuable feedback and if you have any questions or issues about this article, please let me know.

Also, check How To Convert HTML To PDF In Angular 9

2 Comments

  1. Paul

    Nice article! Here’s a little change i made to prevent a nested subscription:

    this._router.events.pipe(
    filter(event => event instanceof NavigationEnd),
    switchMap(() => {
    const childRoute = this._getChild(this._route);
    return childRoute.data;
    })
    ).subscribe({
    next: (data) => {
    this._title.setTitle(data.title);
    }

    0
    0
    Reply
    1. Thanks for your precious suggestion dear 🙂

      0
      0
      Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories