我有一个侧栏和工具栏,在我的每一个不同的页面(主页,关于等)。我想让顶部的工具栏上有反映你所处页面的文字,但我不知道该怎么做。我试着在routerLink旁边实现一个ngIf来检查routerLink是否指向主页,但它不起作用,我不知道还能做什么。
<mat-toolbar >
<button
type="button"
aria-label="Toggle sidenav"
mat-icon-button
(click)="drawer.toggle()">
<mat-icon aria-label="Side nav toggle icon">menu</mat-icon>
</button>
<span *ngIf = "[routerLink]"="[/']">Home</span>
</mat-toolbar>
<ng-content></ng-content>
</mat-sidenav-content>
你可以在你的组件中订阅路由器事件,然后比较activeRoute。
activeRoute: string;
constructor(private router: Router) {
this.router.events.subscribe((event) => {
if(event instanceof NavigationEnd && event.url) {
this.activeRoute = event.url;
}
});
}
现在在你的html中,你可以比较它。
<mat-toolbar >
<button
type="button"
aria-label="Toggle sidenav"
mat-icon-button
(click)="drawer.toggle()">
<mat-icon aria-label="Side nav toggle icon">menu</mat-icon>
</button>
<span *ngIf="activeRoute=='/'">Home</span>
</mat-toolbar>
你可以在路由中提供一些数据
{
path: `main`,
component: MainComponent,
data: {
title: 'Main page'
}
},
然后在组件中你可以捕捉这些数据。
export class MainComponent implements OnInit {
constructor(
private route: ActivatedRoute
) { }
ngOnInit() {
this.route.snapshot.data['title'];
}
}
然后你可以把标题保存在servicetorecomponent属性中,并在你需要的地方提供输入参数。