You are currently viewing How to Set Page Title Based on Route in Angular
Angular

How to Set Page Title Based on Route in Angular

In this post, I will show you how to set page title based on route in Angular.

Angular provides a built-in Title service that we can use to set the title of the web page dynamically from code. We will use the title service in combination with router events to change page title for all routes.

Setting page title in Angular

Firstly, import the Title service in the component you want to set the title:

import { Title } from '@angular/platform-browser';Code language: TypeScript (typescript)

Inject the Title service in the constructor of the component:

constructor(private titleService: Title) {}Code language: TypeScript (typescript)

Then you can use the setTitle method of the Title service to set the title of the web page.

For example, you can set the title based on the data received from a service or from the component’s properties:

this.title.setTitle(`My Awesome App - ${data.title}`);Code language: TypeScript (typescript)

As you can see, it is pretty straightforward to use set the title in Angular.

Setting the title for all routes

Instead of setting the title in every component that’s associated with a route, we’ll take it a step further and dynamically set the title from the routes table.

DRY (don’t repeat yourself) is a principle in software development that recommends to do something once, and only once.

The first step is to update routes table in every feature module to hold page titles.

const routes: Routes = [
  {
    path: "",
    component: HomePageComponent,
    data: {
      title: "Home"
    }
  },
  {
    path: "blog",
    component: BlogPageComponent,
    data: {
      title: "Blog"
    }
  },
  {
    path: "**",
    component: NotFoundPageComponent,
    data: {
      title: "Not Found"
    }
  }
];
Code language: TypeScript (typescript)

You should now go through all routes of your app and make sure there is a title associated with every route!

Next, generate a service to get data from the current route:

ng generate service route-dataCode language: Bash (bash)

Implement the service with below code:

import { Injectable } from "@angular/core";
import { ActivatedRoute, ActivatedRouteSnapshot, Data } from "@angular/router";

@Injectable({
  providedIn: "root"
})
export class RouteDataService {

  constructor(private route: ActivatedRoute) { }

  get(): Data {
    return this.getRouteSnapshot().data;
  }

  private getRouteSnapshot(): ActivatedRouteSnapshot {
    let route = this.route;

    while (route.firstChild) {
      route = route.firstChild;
    }

    return route.snapshot;
  }
}
Code language: TypeScript (typescript)

This service allows us to pull out the data object we defined in our routes earlier.

Like any other singleton service, we can inject it into any component to set the title.

Since we want to set the title for every page, we need to subscribe to router events in the root component app.component.ts.

Let’s to update app.component.ts to read the title every time navigation occurs:

import { filter } from 'rxjs';

import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { NavigationEnd, Router } from '@angular/router';
import { RouteDataService } from './route-data.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  constructor(private router: Router,
    private routeDataService: RouteDataService,
    private title: Title) {
  }

  ngOnInit(): void {
    this.router.events
      .pipe(filter(event => event instanceof NavigationEnd))
      .subscribe(_ =>
        this.title.setTitle(`${this.routeDataService.get()["title"]} - Umut Esen`)
      );
  }
}

Code language: TypeScript (typescript)

By using this method, you can set the title of the web page dynamically based on the data from the router events, which will update the title of the window in real-time.

Conclusion

In summary, we learned how to set the page title in Angular. Through DRY principle, we implemented a feature that sets the page title based on Angular router events.

Let me know what you think by dropping a comment below!

Umut Esen

I am a software developer and blogger with a passion for the world wide web.

Leave a Reply