how to change page title in angular2 router

后端 未结 14 1311
深忆病人
深忆病人 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:06

    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+.

提交回复
热议问题