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.
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.
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.
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"); }
}