Dynamic Page Title Based On Route In Angular

Dynamic Page Title Based On Route In Angular

Discover how to use Angular's Title Service to set a dynamic page title based on a route. Using Angular's Title service, we learned how to set the page title. It can be laborious to set the title in each component. You might overlook some of the elements. Defining the title together with the routes and using them to update the title is the easier solution. We'll use the Angular route data Property to accomplish that.

Example App

Create a new angular app.

Add five Angular Components. HomeComponent, OneComponent, TwoComponent, ThreeComponent & TwoAComponent

Add the following code under the home.component.ts:

import { Component} from '@angular/core';
 
 
@Component({
  template: `<h1>Home Component</h1>
              `
})
export class HomeComponent   {
}

Add the following code under the one.component.ts:

import { Component } from '@angular/core';
 
@Component({
  template: `<h1>One Component</h1>`
})
export class OneComponent{
}

Add the following code under the two.component.ts:

import { Component} from '@angular/core';
 
 
@Component({
  template: `<h1>Two Component</h1> 
            <router-outlet></router-outlet>
              `
})
export class TwoComponent  {
 
 
}

Add the following code under the three.component.ts:

import { Component} from '@angular/core';
 
 
@Component({
  template: `<h1>Three Component</h1>`
})
export class ThreeComponent {
}

Add the following code under the two-a.component.ts:

import { Component  } from '@angular/core';
 
 
 
@Component({
  template: `<h1>Two A Component</h1>`
})
export class TwoAComponent   {
 
 
}

Import Title Service

As seen below, open the app.module.ts file and import the Title Service from the @angular/platform-browser. Also, register the Title service using the Angular Providers metadata.

import { BrowserModule, Title } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
 
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { OneComponent } from './one.component';
import { TwoComponent } from './two-component';
import { ThreeComponent } from './three.component';
import { TwoAComponent } from './two-a.component';
import { HomeComponent } from './home.component';
 
@NgModule({
  declarations: [
    AppComponent,OneComponent,TwoComponent,ThreeComponent,TwoAComponent, HomeComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [Title],
  bootstrap: [AppComponent]
})
export class AppModule { }

Define the title in Routes

Open the routes and the app-routing.module.ts as shown below. In the route data, add the title attribute. Static or dynamic data can be passed to routed components via route data.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { OneComponent } from './one.component';
import { TwoComponent } from './two-component';
import { ThreeComponent } from './three.component';
import { TwoAComponent } from './two-a.component';
import { HomeComponent } from './home.component';
 
 
const routes: Routes = [
  {path:'',component:HomeComponent, data : {title:'Title for Home Component'}},
  {path: 'one', component:OneComponent, data :{ title:'Title for One Component'}},
  {path: 'two', component:TwoComponent, 
      data :{ title:'Title for Two Component'},
      children: [
          {path:'a',component:TwoAComponent, data : {title:'title for two a component'}}
      ]
    },
  {path: 'three', component:ThreeComponent, data :{ title:'Title for three Component'}},
];
 
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Listen to Navigation Changes

Knowing when the path changes is the key to changing the title. By paying attention to the NavigationEnd event, we may perform this.

Additionally, every route change event in the app needs to be listened to. The topmost component in our app is called app.component.ts. When the app opens, it loads. It endures for the duration of the app. Therefore, app.component.ts is the best area to listen to route modifications.

The code for the app.component.ts is as follows.

import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { filter, map } 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(() => {
 
        var 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;
    }
 
  }
 
}

First, we add the services Router, ActivatedRoute, and Title to our constructor.

We monitor the router events in ngOnInit. We just pay attention to the NavigationEnd event by using the filter operator.

The previous loaded component's ActivateRoute must be located. In order to obtain the bottom-most Activate Route, we therefore recursively traverse the Router Tree using the firstChild attribute of the ActivatedRoute. To do that, we employ the getChild method.

All we have to do to obtain the title recorded in the route data is subscribe to the Route data once we have obtained the ActivateRoute of the most recently loaded component.

Lastly, set the Title tag using the setTitle of the Title service.

Dynamic Page Title Route In Angular

Conclusion

Using Angular Routes, we learned how to set a dynamic page title.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post