Angular 9|8|7 Set Title Dynamically on Route Change

The traditional website has pages that are loaded while refreshing the whole website or sometimes rerendered using dynamic languages like PHP from the server-side. Such websites can have title tags on each page which can be dynamic or manually placed on static HTML pages.

Single page application (SPA) like Angular where only one page i.e index.html is loaded in the browser that only once, we can’t change title tag content on page routing. Different pages in SPA is basically a component with a template attached, so we may need some other way to show different title value for each Routed page.

The title can help a user to easily identify without even opening, which page is currently opened on a tab.

How to change Titles in Angular Application?

Luckily,  the team has taken care of this problem faced in a SPA.

The @angular/platform-browser package provides Title class with the following two methods:

<strong>setTitle()</strong> : Set the title of the current HTML document.
<strong>getTitle()</strong>: Get the title of the current HTML document.

Dynamically Change Title on Routing

Now we have an option to change Title using setTitle() method, But do we need to add it to every component?

Let’s do it in a simple a stop way!

 

Step 1) Create a service or use any global service you already have in your project.

Define some reusable methods:

If the current URL in the browser is <em>http://example.com/user/profile</em>

The parentUrl() will return ‘user’ and childUrl() returns ‘profile’.

The Ucase() method just capitalizes the first character of the string passed 🙂

// common.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Title } from '@angular/platform-browser';

@Injectable()
export class CommonService {

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

    // Get Parent Route if any
    parentUrl() {
        return this.router.url.split('/')[1];
    }

    // Get Child Route if any
    childUrl() {
        return this.router.url.split('/')[2];
    }

    // Set Title
    setTitle(newTitle: string) {
        this.titleService.setTitle(newTitle);
    }

    // Uppercase First
    Ucase(name: string) {
        return name.charAt(0).toUpperCase() + name.slice(1);
    }
}

 

Step 2) Now open app.component.ts file and add the router event subscription as shown below:

// app.component.ts
import { Component } from '@angular/core';
import { Router, NavigationEnd, Event } from '@angular/router';
import { CommonService } from './shared/services/global/common.service';

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

    constructor(
        public router: Router,
        private commonService: CommonService
    ) {
        this.router.events.subscribe((event: Event) => {
            if (event instanceof NavigationEnd) {

                this.commonService.setTitle('Dynamic Title : FreakyJolly.com');
            }
        });
    }
}

Here we are subscribing the router event hooks with instanceof NavigationEnd which is triggered when routing is completed and come to end.

In this, we are calling our common service method setTitle to change Title dynamically with current route values.

 

 

Leave a Comment

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