by Sai gowtham

How to set a document title in Angular app

In this tutorial, we are going to learn about setting a document title in the angular (routes) using the TitleService.

What is Title service?

The Title service is a simple API that is used for setting and getting the document title to the current webpage. It is part of the angular Browser platform.

getTitle() method : It is used to get the title.

setTitle() method : It is used to set the title.

Setting the document title

To use the Title service inside our components, first we need to register a Title Service in the root application module that is app.module.ts file.

Open your app.module.ts file and import the Title service from the @angular/platform-browser package then add it to the providers array.

app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule, Title } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, HelloComponent ],
  providers:    [Title],  bootstrap:    [ AppComponent ]
})

export class AppModule { }

Now, we can set a new document title by injecting a Title service into the Component constructor.

app.component.ts
import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})

export class AppComponent  {

  public constructor(private titleService: Title){
    this.titleService.setTitle("Home page");  }

}

Similarly, you can use the same procedure to set a document title to the other routing components in your angular app.

contact.component.ts
import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: [ './contact.component.css' ]
})

export class ContactComponent  {

  public constructor(private titleService: Title){
    this.titleService.setTitle("Contact page");  }

}

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course