需要根据路线在我的 header 中设置不同的按钮
Need to have different buttons in my header based on the route
这个不是很复杂,但我只是不知道 angular 中的方法。
所以,假设我的应用程序中有以下路线
/
/bar
/foo
在我的 header 中,我总是有一个按钮,根据活动路线,它是汉堡包或后退按钮;如果我在“/”路线上,我需要汉堡按钮,对于所有其他路线,我需要后退按钮
<header>
<button *ngIf="!isRoot">Back</button>
<button *ngIf="isRoot">Hamburger</button>
</header>
<router-outlet></router-outlet>
在我的 AppComponent 中使用以下代码
this.router.events
.subscribe(
(event: NavigationEvent) => {
if (event instanceof ActivationStart) {
this.isRoot = !!event.snapshot.url[0]?.path; // is empty string for /
}
});
如果我在我的应用程序中导航,这会很好用,但如果我点击重新加载则不会,因为这不是路线更改,也不会触发上面的代码。现在,在我开始 window.location 之前,我想知道是否还有什么可以用 ActivatedRoute 做的。有什么建议吗?
对于初始加载,您可以使用 this.router.url
而不是依赖 NavigationEvent,例如:
this.isRoot = this.router.url === '/';
这个不是很复杂,但我只是不知道 angular 中的方法。
所以,假设我的应用程序中有以下路线
/
/bar
/foo
在我的 header 中,我总是有一个按钮,根据活动路线,它是汉堡包或后退按钮;如果我在“/”路线上,我需要汉堡按钮,对于所有其他路线,我需要后退按钮
<header>
<button *ngIf="!isRoot">Back</button>
<button *ngIf="isRoot">Hamburger</button>
</header>
<router-outlet></router-outlet>
在我的 AppComponent 中使用以下代码
this.router.events
.subscribe(
(event: NavigationEvent) => {
if (event instanceof ActivationStart) {
this.isRoot = !!event.snapshot.url[0]?.path; // is empty string for /
}
});
如果我在我的应用程序中导航,这会很好用,但如果我点击重新加载则不会,因为这不是路线更改,也不会触发上面的代码。现在,在我开始 window.location 之前,我想知道是否还有什么可以用 ActivatedRoute 做的。有什么建议吗?
对于初始加载,您可以使用 this.router.url
而不是依赖 NavigationEvent,例如:
this.isRoot = this.router.url === '/';