我需要从子路由视图设置标题...
我有父组件:
@Component({
selector: 'parent-component',
template: `
<header>{{headerTitle}}</header>
<router-outlet></router-outlet>
`,
directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
{ path: '/link1', name: 'Link1', component: Link1Component, useAsDefault: true },
{ path: '/link2', name: 'Link2', component: Link2Component },
])
export class ParentComponent {
public sharedHeaderTitle: string;
constructor(public router: Router) { }
}
有一个孩子的路由选项卡:
@Component({
template: '<div></div>'
})
export class Link1Component {
public headerTitle: string;
constructor() {
this.headerTitle = "Link1 page";
}
}
和另一个
@Component({
template: '<div></div>'
})
export class Link2Component {
public headerTitle: string;
constructor() {
this.headerTitle = "Link2 page";
}
}
我在这里找到的亲子关系如何,但它不适用于路由......
制作方法是什么?
解决
我找到了一个解决方案,认为这是最好的方法:
http://plnkr.co/edit/LYTXmY9Fwm8LwumICWDT
Link1Component
和Link2Component
需要与ParentComponent
通信。由于它们被限制在路由器插座中,因此我不确定除了订阅路由器事件之外这是否可行(请参阅如何在 Angular 2 中检测路由更改?
我还会考虑稍微改变一下设计,并将设置标题的责任转移到ParentComponent
,即ParentComponent
在发出 router.navigate(['LinkXComponent']
命令之前设置标题。
我希望这有帮助