Angular 2 - Check current active route “name”

后端 未结 6 1585
说谎
说谎 2020-12-24 09:36

I am having an Angular 2 application with several nested children view. But it will be displayed on the same page though several router-outlet.



        
6条回答
  •  囚心锁ツ
    2020-12-24 10:01

    name was removed quite some time ago from routes, but routes allow to add arbitrary data

    const routes: RouterConfig = [
        {
            path: '',
            redirectTo: '/login',
            pathMatch: 'full',
        },
        {
            path: 'login',
            component: LoginComponent,
            data: {title: 'Login'}
        },
        {
            path: 'home',
            component: HomeComponent,
            data: {title: 'Home'}
        },
        {
            path: 'wepays',
            component: WePaysComponent,
            data: {title: 'WePays'}
        }
    ];
    

    This code constructs a title from the names of all route segments. This could probably be simplified for your use case.

    export class AppComponent { 
      constructor(titleService:Title, router:Router, activatedRoute:ActivatedRoute) {
        router.events.subscribe(event => {
          if(event instanceof NavigationEnd) {
            var title = this.getTitle(router.routerState, router.routerState.root).join('-');
            console.log('title', title);
            titleService.setTitle(title);
          }
        });
      }
    
      // collect that title data properties from all child routes
      // there might be a better way but this worked for me
      getTitle(state, parent) {
        var data = [];
        if(parent && parent.snapshot.data && parent.snapshot.data.title) {
          data.push(parent.snapshot.data.title);
        }
    
        if(state && parent) {
          data.push(... this.getTitle(state, state.firstChild(parent)));
        }
        return data;
      }
    }
    

    See also Changing the page title using the Angular 2 new router

提交回复
热议问题