I am trying to change the page title from the router, can this be done?
import {RouteConfig} from \'angular2/router\';
@RouteConfig([
{path: \'/home\', com
For Angular 4+:
If you want to use route custom data to define page title for every route path, the following approach will work for the nested routes and with angular version 4+:
You can pass page title in your route definition:
{path: 'home', component: DashboardComponent, data: {title: 'Home Pag'}},
{path: 'about', component: AboutUsComponent, data: {title: 'About Us Page'}},
{path: 'contact', component: ContactUsComponent, data: {title: 'Contact Us Pag'}},
Now, most important in your upper level component (ie AppComponent), you can globally catch the route custom data on every route change and update the page title:
import {Title} from "@angular/platform-browser";
import { filter, map } from 'rxjs/operators';
export class AppComponent implements OnInit {
constructor(
private activatedRoute: ActivatedRoute,
private router: Router,
private titleService: Title
) { }
ngOnInit() {
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( (title: any) => {
this.titleService.setTitle(title);
});
}
The above code is tested against angular verion 4+.