使用Angular 2新路由器更改页面标题 [英] Changing the page title using the Angular 2 new router

查看:58
本文介绍了使用Angular 2新路由器更改页面标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用新路由器时,在浏览器中更改应用页面标题的正确方法是什么?

What's the right way to change the app page title in browser when using the new router?

*使用Angular 2 CLI

*Using Angular 2 CLI

推荐答案

可以使用

The title can be set using the Title service

要从当前路线中获取标题,可以使用data属性.

To get the title from the current route the data property could be used.

柱塞示例

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'}
    }
];

export class AppComponent { 
  constructor(titleService: Title, router: Router) {
    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;
  }
}

刚刚找到 https://github.com/angular/angular/issues/9662#issuecomment-229034288 ,其中演示了类似的方法.

Just found https://github.com/angular/angular/issues/9662#issuecomment-229034288 where a similar approach is demonstrated.

我还找到了 https://toddmotto.com/dynamic-page -titles-angular-2-router-events 加上一些更漂亮的代码.

I also found https://toddmotto.com/dynamic-page-titles-angular-2-router-events with bit a more beautiful code.

这篇关于使用Angular 2新路由器更改页面标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆