In Angular, you can set different page titles for every route using the Title
service provided by the @angular/platform-browser
package. You can inject the Title
service in your component and set the title using the setTitle()
method. Here is an example:
Import the Title
service in your component:
Inject the Title
service in your component's constructor:
Note: You can also set the title dynamically by using a parameter or data from the route. To do this, you can access the
ActivatedRoute
service and get the route data using thedata
property. For example:
import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { filter, map } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private router: Router,
private activatedRoute: ActivatedRoute,
private titleService: Title) {
}
ngOnInit() {
this.router.events.pipe(
filter(event => event instanceof NavigationEnd),
)
.subscribe(() => {
var rt = this.getChild(this.activatedRoute)
rt.data.subscribe(data => {
console.log(data);
this.titleService.setTitle(data.title)})
})
}
getChild(activatedRoute: ActivatedRoute) {
if (activatedRoute.firstChild) {
return this.getChild(activatedRoute.firstChild);
} else {
return activatedRoute;
}
}
}
First, we inject Router
, ActivatedRoute
& Title
services in our constructor
In ngOnInit, we listen to the router events. We use the filter
operator to listen to only to the NavigationEnd
event.
We need to find the ActivateRoute
of the last loaded component. Hence, we use the firstChild
property of the ActivatedRoute
to recursively traverse through the Router Tree to get the bottom-most Activate Route. We use the getChild
method to do that.
Once, we get the ActivateRoute
of the last loaded component, all we need to do is subscribe
to the Route, data to get the title stored in the route data.
Finally, use the setTitle
of the Title service to set the Title tag