I would prefer to add a wrapper class just to make sure that i will not change everywhere if import {Title} from "@angular/platform-browser"; changed in the upcoming release :) ... Maybe Something called "AppTitleService"
import { Injectable } from '@angular/core';
import { Title } from '@angular/platform-browser';
@Injectable({ providedIn: 'root' })
export class AppTitleService {
constructor(private titleService: Title) { }
getTitle() {
this.titleService.getTitle();
}
setTitle(newTitle: string) {
this.titleService.setTitle(newTitle);
}
}
Here is tested way to set page title on Angular 8 but you can use it on Angular 5 as well.
Once you set this you have to just set title on route file and all will set automatically.
import { Component } from '@angular/core';
import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { filter, map } from "rxjs/operators";
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
constructor (private router: Router, private activatedRoute: ActivatedRoute, private titleService: Title) {
this.router.events.pipe(
filter(event => event instanceof NavigationEnd),
map(() => {
let child = this.activatedRoute.firstChild;
while (child) {
if (child.firstChild) {
child = child.firstChild;
} else if (child.snapshot.data && child.snapshot.data['title']) {
return child.snapshot.data['title'];
} else {
return null;
}
}
return null;
})
).subscribe( (data: any) => {
if (data) {
this.titleService.setTitle(data + ' - Website Name');
}
});
}
}
In Angular v14, there is a built-in strategy service for collecting the title from the route based on the primary router outlet, and setting the browser's page title.
Today is 2022-10-14. Answers above including Angular's own doc are very good, but not the easiest/lightest, and sometimes tedious.
We have hundreds of components/pages, Angular 12+, title and <meta name="description" ...> are typically static, so the best way is hardcode without adding any packages:
<head>
<title...>
<meta ...>
...
</head>
While Chrome and Edge, including META SEO inspector show all title and meta from index.html and components, browsers display only the firsttitle in the order of discovery.
Solution:
Move <title> and <meta> of index.html to bottom
Every component/page to have its own else default to index’s
Reasons:
<head> is no longer mandatory in HTML5 whom was released in 2014
<title> and <meta> can be placed anywhere
They are allowed to have multiple entries even for the same duplicated name
<title>, first discovered will be used for display so component/page’s shows
With one simple adjustment inside of index.html, Wa-La, all pages display the corresponding title. No need to introduce any new component/package and update hundreds of files, and SEO 100!
BTW, this is not just for Angular, apply to all others including .NET, Vue and React.