Angular2路由器V3和菜单选择
我希望我的菜单通过在菜单项(如Ng1)上基于当前路由应用“活动”类来显示当前路由Angular2路由器V3和菜单选择,angular,router,angular2-changedetection,Angular,Router,Angular2 Changedetection,我希望我的菜单通过在菜单项(如Ng1)上基于当前路由应用“活动”类来显示当前路由 @Component({ moduleId: module.id, selector: 'main-menu', directives: [ ROUTER_DIRECTIVES, ], template: ' <paper-button #menu1 [data]="['/app/collection']" [routerLink]="['/app/collection']" [n
@Component({
moduleId: module.id,
selector: 'main-menu',
directives: [
ROUTER_DIRECTIVES,
],
template: '
<paper-button #menu1 [data]="['/app/collection']" [routerLink]="['/app/collection']" [ngClass]="{active: isActive(menu1.data)}">My Collection</paper-button>
<paper-button #menu2 [data]="['/app/book/find']" [routerLink]="['/app/book/find']" [ngClass]="{active: isActive(menu2.data)}">Browse Books</paper-button>'
})
export class MainMenuComponent {
public current:string;
constructor(public router:Router, private changeDetector:ChangeDetectorRef) {
this.router.events.subscribe((e)=> {
this.current = e.url;
});
}
ngOnInit() {
this.changeDetector.detectChanges();
}
isActive(data) {
if (data) {
return this.current == data[0];
}
}
}
@组件({
moduleId:module.id,
选择器:“主菜单”,
指令:[
路由器指令,
],
模板:'
我的收藏
浏览书籍
})
导出类MainMenuComponent{
公共电流:字符串;
构造函数(公共路由器:路由器,专用changeDetector:ChangeDetectorRef){
this.router.events.subscribe((e)=>{
this.current=e.url;
});
}
恩戈尼尼特(){
this.changeDetector.detectChanges();
}
isActive(数据){
如果(数据){
返回this.current==数据[0];
}
}
}
这是可行的,但有两个问题我需要一些帮助来解决:
1) 我需要调用this.changeDetector.detectChanges()代码>否则在页面的初始加载时不会应用活动类。(我不明白为什么这不是开箱即用…)
2) 关于模板,我还没有找到一种不在routerLink中重复我自己的方法。我希望能够传递对我的数据的引用,比如menu2.data
,但它不起作用
如果您有任何帮助/建议,我们将不胜感激。在新路由器中,您可以定义当路由处于活动状态时,应向路由器链接添加什么类:
<a [routerLink]="['/app/collection']" [routerLinkActive]="['active']">Home</a>
主页