how to change page title in angular2 router

后端 未结 14 1290
深忆病人
深忆病人 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 17:09

    Here's my approach which works fine, especially for nested routes:

    I use a recursive helper method to grab the deepest available title after a route has changed:

    @Component({
      selector: 'app',
      template: `
        

    {{title | async}}

    ` }) export class AppComponent { constructor(private router: Router) { this.title = this.router.events .filter((event) => event instanceof NavigationEnd) .map(() => this.getDeepestTitle(this.router.routerState.snapshot.root)); } title: Observable; private getDeepestTitle(routeSnapshot: ActivatedRouteSnapshot) { var title = routeSnapshot.data ? routeSnapshot.data['title'] : ''; if (routeSnapshot.firstChild) { title = this.getDeepestTitle(routeSnapshot.firstChild) || title; } return title; } }

    This is assuming, that you have assigned page titles within the data property of your routes, like this:

    {
      path: 'example',
      component: ExampleComponent,
      data: {
        title: 'Some Page'
      }
    }
    

提交回复
热议问题