Setting page titles was not natively available (without Angular Universal) in Angular applications prior to the version 14. Angular introduced a new property title to route objects using which we can easily set page titles.
Setting Static Page Titles in Angular 14+ Applications
Setting Static page titles is straight forward thing in Angular 14+ applications. All we need to do is to set a value to the title property of route object.
example:
const routes: Routes = [
{ path: '', component: HomeComponent, title: "Home - Angular 14 Application" },
{ path: 'user', component: UserComponent, title: "User Dashboard" }
];
HTML:
<a routerLink="/"> Home </a>
<a routerLink="/user"> User </a>
<hr>
<router-outlet></router-outlet>
With the above code in place, the output may look something like this
Home Page
User Page
Setting Dynamic Page Titles in Angular 14+ Applications
Many times we may want to set page titles dynamically. Suppose we have routes like this
const routes: Routes = [
{ path: '', component: HomeComponent},
{ path: 'user/:id', component: UseridComponent}
];
Here, we may want to set the title of the page based on the id of the user. To achieve this functionality, we need to implement custom strategy to set the titles.
To implement custom title strategy, we need to create a service and extend the built-in TitleStrategy of angular. When we extend the TitleStrategy, we need to override updateTitle method to which angular passes RouterStateSnapshot parameter. Based on this RouterStateSnapshot, we can set the titles based on the url.
example:
import { Injectable } from '@angular/core';
import { RouterStateSnapshot, TitleStrategy } from '@angular/router';
@Injectable({ providedIn: 'root' })
export class DynamicTitleStrategy extends TitleStrategy {
override updateTitle(routerStateSnapshot: RouterStateSnapshot): void {
const title = this.buildTitle(routerStateSnapshot);// if you have set title in the route, you can access it like this
if (routerStateSnapshot.url === '/') {
document.title = "Home - Angular 14 Application"
} else {
if (routerStateSnapshot.root.firstChild?.url[0].path === 'user') {
document.title = ` Welcome ${routerStateSnapshot.root.firstChild?.paramMap.get('id')} `
} else {
document.title = "Default Title"
}
}
}
}
Based on your application requirements, you can change the conditions.
Now, we need to provide it to the module through providers array
...
providers: [{ provide: TitleStrategy, useClass: DynamicTitleStrategy }],
...
with this, now we can have some HTML like this
<a routerLink="/"> Home </a>
<a routerLink="/user/john"> John </a>
<a routerLink="/user/james"> James </a>
<hr>
<router-outlet></router-outlet>
Now the output will be something like this
Leave A Comment