Bad*_*bet 13 angular angular-router
我有一个Angular 5应用程序.
我的app组件中有以下代码.
我想隐藏特定路线的导航栏和顶部栏.
是否有可能获得当前激活的路线app.component.ts?如果是的话,怎么样?
如果不可能,有没有解决方案来解决这个问题(使用警卫或其他什么......)?
还要记住,它应该是被动的.当我切换到另一个路线边栏时,导航栏应该再次显示.
Tom*_*ula 10
尝试这个:
在app.component.ts中
import { Component } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import { filter, map, mergeMap } from 'rxjs/operators';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
showSidebar$: Observable<boolean>;
private defaultShowSidebar = true;
constructor(
private router: Router,
private activatedRoute: ActivatedRoute,
) {
this.showSidebar$ = this.router.events.pipe(
filter(e => e instanceof NavigationEnd),
map(() => activatedRoute),
map(route => {
while (route.firstChild) {
route = route.firstChild;
}
return route;
}),
mergeMap(route => route.data),
map(data => data.hasOwnProperty('showSidebar') ? data.showSidebar : this.defaultShowSidebar),
)
}
Run Code Online (Sandbox Code Playgroud)
app.component.html
<aside *ngIf="showSidebar$ | async">Sidebar here</aside>
<router-outlet></router-outlet>
<a routerLink="/without-sidebar">Without sidebar</a>
<a routerLink="/with-sidebar">With sidebar</a>
<a routerLink="/without-data">Without data.showSidebar</a>
Run Code Online (Sandbox Code Playgroud)
应用程式路线
RouterModule.forRoot([
{ path: 'with-sidebar', component: WithSidebarComponent, data: { showSidebar: true } },
{ path: 'without-sidebar', component: WithoutSidebarComponent, data: { showSidebar: false } },
{ path: 'without-data', component: WithoutDataComponent },
])
Run Code Online (Sandbox Code Playgroud)
您可以根据需要对其进行修改。