Angular | How to change page title with routing in Angular?

So, to day’s blog is on How to set dynamic page title based on Route in Angular using Title Service, offered by Angular.

First of all what is Title Service?

Title service can be used to get and set the title of a current HTML document.

Since an Angular application can’t be bootstrapped on the entire HTML document (<html> tag) it is not possible to bind to the text property of the HTMLTitleElement elements (representing the <title> tag). Instead, this service can be used to set and get the current title value.

How many methods are there for Title?

There are only two methods..

class Title {
  getTitle(): string
  setTitle(newTitle: string)
}

getTitle()

Get the title of the current HTML document.

getTitle(): string

Parameters: There are no parameters.

Returns: string

setTitle()

Set the title of the current HTML document.

setTitle(newTitle: string)

Parameters: newTitle: string

How to use getTitle() and setTitle() in Angular project?

import {DOCUMENT, ɵgetDOM as getDOM} from '@angular/common';
import {Inject, Injectable, ɵɵinject} from '@angular/core';

/**
 * create Title service.
 */
export function createTitle() {
  return new Title(ɵɵinject(DOCUMENT));
}
@Injectable({providedIn: 'root', useFactory: createTitle, deps: []})
export class Title {
  constructor(@Inject(DOCUMENT) private _doc: any) {}
  /**
   * Get the title of the current HTML document.
   */
  getTitle(): string {
    return this._doc.title;
  }

  /**
   * Set the title of the current HTML document.
   * @param newTitle
   */
  setTitle(newTitle: string) {
    this._doc.title = newTitle || '';
  }
}

or you can just set Title like this

import {Title} from "@angular/platform-browser";

....

constructor(private titleService:Title) {
  this.titleService.setTitle("Some title");
}

So, this is how you can set Title on dynamic route.

Thank you for reading and stay tune, stay connected and stay safe. Please support us by sharing the blog.

Read our other blogs on ITbulls.in

Previous Post
Next Post

Leave a Reply

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

14 − twelve =