角度2路径参数数据

时间:2017-02-15 09:53:18

标签: angular angular2-routing

我有一个带有1个参数的简单路线:

{
    path: 'item/:id',
    component: ItemComponent,
    data: {title: 'Item detail'}
}

我正在使用主AppComponent中的数据标题属性设置页面标题:

export class AppComponent implements OnInit {
    title: string;

    ngOnInit() {
         this.router.events
         .. parse it
         .subscribe((event) => {
                this.title = event['title'];
         });
    }
}

然后我只是在AppComponent模板中显示它:

<h1>{{ title }}</h1>

问题是我是否想拥有像"Item detail #name(:id)"这样的动态标题。有什么方法可以添加例如将param(:id)或变量路由到数据标题属性?像

这样的东西
{
    path: 'item/:id',
    component: ItemComponent,
    data: {title: 'Item detail #' + :id }
}

1 个答案:

答案 0 :(得分:2)

就像我在评论中所说,您可以将data.title参数作为蓝图保留,并从组件中替换动态部分。

路线声明:

{
  path: 'item/:id',
  component: ItemComponent,
  data: { title: 'Item detail [id]' }
}

data.title中,我写了[id]以使替换更容易,但可以随意使用您想要的字符串来替换字符串。

然后,在组件中:

export class AppComponent {
  title: string;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    const titlePattern = this.route.snapshot.data['title'];
    const id = this.route.snapshot.params['id'];
    this.title = titlePattern.replace('[id]', id);
  }
}
相关问题