Angular

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

Yasin Panwala

Yasin Panwala is a Web Developer and Author at TheCodeHubs. He has experience in Web Developing and Designing and also in Writing. He has got his skills in working on technologies like .NET Core, ADO.NET, AJAX, Angular, AngularJS, ASP.NET, ASP.NET MVC, Bootstrap, C#, CSS, Entity Framework, Express.js, GraphQL, HTML, JavaScript, JQuery, JSON, LINQ, Microsoft Office, MongoDB, MySQL, Node.js, PostgreSQL, SQL, SQL Server, TypeORM, TypeScript, Visual Basic .NET, Web API. He also got his skills in working with different integration and some known versioning tools. He is always ready to learn new things and he always tries his best on tasks that are assigned to him and gives the best possible outputs.

View Comments

  • 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);
    }

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago