In this article, I'll show you how to dynamically change page title of an Angular app based on Route configuration.
Let say we have three components HomeComponent, MainComponent and AboutComponent. The corresponding route definition as in app-routing.module.ts file
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { AboutComponent } from "./about/about.component";
import { HomeComponent } from "./home/home.component";
import { MainComponent } from "./main/main.component";
const routes: Routes = [
{ path: "", redirectTo: "home", pathMatch: "full" },
{ path: "home", component: HomeComponent, data: { title: "Home Page" } },
{ path: "main", component: MainComponent, data: { title: "Main Page" } },
{ path: "about", component: AboutComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
Here we have defined custom title for HomeComponent and MainComponent in the data section.
In app.component.ts file we need to subscribe for router events and populate the page title
import { Component, OnInit, VERSION } from "@angular/core";
import { Title } from "@angular/platform-browser";
import { ActivatedRoute, NavigationEnd, Router } from "@angular/router";
import { filter, map, mergeMap } from "rxjs/operators";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
name = "Angular " + VERSION.major;
constructor(
private router: Router,
private activatedRoute: ActivatedRoute,
private titleService: Title
) {}
ngOnInit(): void {
this.router.events
.pipe(
filter(event => event instanceof NavigationEnd),
map(() => {
let route = this.activatedRoute;
while (route.firstChild) route = route.firstChild;
return route;
}),
filter((route: any) => route.outlet === "primary"),
mergeMap((route: any) => route.data),
map((data: any) => {
if (data.title) {
return data.title;
} else {
return "Default App Title";
}
})
)
.subscribe(pathString => this.titleService.setTitle(pathString));
}
}
Define navigations in app.component.html file as
<a routerLink='home'>Home</a>
<a routerLink='main'>Main</a>
<a routerLink='about'>About</a>
<router-outlet></router-outlet>
As you navigate the pages, you can see the page title as set in app-routing.module.ts file.
Hope this helps!