how to change page title in angular2 router

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

    Angular 6+

    if route configured as follow :-

    Routes = [
         {  path: 'dashboard',
           component: DashboardComponent,
           data: {title: 'Dashboard'}
       }]
    

    **Then in component constructor title can be set as follow :- **

     constructor( private _titleService: Title, public activatedRoute: ActivatedRoute) {
        activatedRoute.data.pipe(map(data => data.title)).subscribe(x => this._titleService.setTitle(x));
       }
    
    0 讨论(0)
  • 2020-12-04 17:05
    import {Title} from "@angular/platform-browser"; 
    @Component({
      selector: 'app',
      templateUrl: './app.component.html',
      providers : [Title]
    })
    
    export class AppComponent implements {
       constructor( private title: Title) { 
         this.title.setTitle('page title changed');
       }
    }
    
    0 讨论(0)
  • 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+.

    0 讨论(0)
  • 2020-12-04 17:08

    Working fine in Angular 6 and 6+ with Pipe and map method instead of using filter

    Step1: routing setup

    {path: 'dashboard', component: DashboardComponent, data: {title: 'My Dashboard'}},
    {path: 'aboutUs', component: AboutUsComponent, data: {title: 'About Us'}},
    {path: 'contactUs', component: ContactUsComponent, data: {title: 'Contact Us Page'}},
    

    step2: in your app.module.ts import module

    import { BrowserModule, Title } from '@angular/platform-browser';
    

    then in provider add providers: [title]

    Step 3 In your main component import

    import { Title } from "@angular/platform-browser";
    import { RouterModule, ActivatedRoute, Router, NavigationEnd } from "@angular/router";
    import { filter, map } from 'rxjs/operators';
    
    constructor(private titleService: Title, private router: Router, private activatedRoute: ActivatedRoute) {
    
        }
    
    ngOnInit() {
    
        this.router.events.pipe(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 => {
            this.titleService.setTitle(title);
        });
    
    }
    
    0 讨论(0)
  • 2020-12-04 17:08

    Here's the simplest way to change the Title of the page, when pages/views are navigated (Tested as of Angular @2.3.1). Simply apply the following solution to all the views you have and you should be good to go:

    Example Code in About Us page/view:

    import {Title} from "@angular/platform-browser";
    
    export class AboutUsComponent implements OnInit {
    
      constructor(private _titleService: Title) {
      }
    
      ngOnInit() {
        //Set page Title when this view is initialized
        this._titleService.setTitle('About Us');
      }
    
    }
    

    Example Code in Contact Us page/view:

    import {Title} from "@angular/platform-browser";
    
    export class ContactusComponent implements OnInit {
    
      constructor(private _titleService: Title) {
      }
    
      ngOnInit() {
        //Set page Title
        this._titleService.setTitle('Contact Us');
      }
    
    }
    
    0 讨论(0)
  • 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: `
        <h1>{{title | async}}</h1>
        <router-outlet></router-outlet>
      `
    })
    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<string>;
    
      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'
      }
    }
    
    0 讨论(0)
提交回复
热议问题