how to change page title in angular2 router

后端 未结 14 1251
深忆病人
深忆病人 2020-12-04 16:17

I am trying to change the page title from the router, can this be done?

import {RouteConfig} from \'angular2/router\';
@RouteConfig([
  {path: \'/home\', com         


        
14条回答
  •  温柔的废话
    2020-12-04 16:46

    This is what I went with:

    constructor(private router: Router, private title: Title) { }
    
    ngOnInit() {
        this.router.events.subscribe(event => {
            if (event instanceof NavigationEnd) {
                this.title.setTitle(this.recursivelyGenerateTitle(this.router.routerState.snapshot.root).join(' - '));
            }
        });
    }
    
    recursivelyGenerateTitle(snapshot: ActivatedRouteSnapshot) {
        var titleParts = [];
        if (snapshot) {
            if (snapshot.firstChild) {
                titleParts = titleParts.concat(this.recursivelyGenerateTitle(snapshot.firstChild));
            }
    
            if (snapshot.data['title']) {
                titleParts.push(snapshot.data['title']);
            }
        }
    
        return titleParts;
    }
    

提交回复
热议问题