问题描述
当我登录到我的管理面板时,我需要从我的主主页隐藏某些组件,如导航栏和页脚。我的管理组件在调用时基于管理模块进行延迟加载。如果路由不是动态的,例如 /admin/login
、/admin/dashboard
等,那么在管理视图中必要的组件会按预期隐藏。但是如果路由是动态的,例如 /admin/category/:categoryId
或 {,问题就会开始{1}} 并且在这些路由中,导航栏和页脚等必要组件不会隐藏自身。我在必要的组件中使用 /admin/user/:userId
获取路由的动态 ID。下面是我在主页上使用的方法来读取应用程序路由并相应地显示/隐藏组件。
Main.ts
ActivatedRoute
Main.html
import { Router,NavigationEnd } from '@angular/router';
public url: any;
constructor(private router: Router) {
this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
this.url = event.url;
}
})
}
解决方法
您在这里需要的是定义正则表达式并对其进行测试。
或者也许检查一下 string#includes(string)
函数就足够了。我还建议使用更具反应性(类似 rxjs)的方法。
在我的模板上:
<div class="main__container">
<app-navbar *ngIf="canShowNavBar$ | async">
</app-navbar>
<app-footer *ngIf="canShowFooter$ | async">
</app-footer>
</div>
我会在打字稿文件中的哪个位置:
export class YourComponent implements OnInit {
canShowNavBar$: Observable<boolean>;
canShowFooter$: Observable<boolean>;
navigationEvents$: Observable<NavigationEnd>;
constructor(private router: Router){}
ngOnInit() {
// Like this we define the stream of the NavigationEnd events
this.navigationEvents$ = this.router.events.pipe(
filter(event => event instanceof NavigationEnd),// This one is not really needed but we're giving some hints to the typescript compiler
map(event => event as NavigationEnd)
);
// Here we define the stream of booleans that determine whether to show the component or not on your template.
this.canShowNavBar$ = this.navigationEvents$.pipe(
map(event => this.shouldShowNavBar(event.url))
);
// Because actually you check for the same conditions
this.canShowFooter$ = this.canShowNavBar$;
}
shouldShowNavBar(url: string): boolean {
// And here you should test against regular expressions:
switch(true) {
case /\/admin\/dashboard/.test(url):
case /\/admin\/category/.test(url):
// More cases where you should show the navBar
return true;
default: return false;
}
}
}
您可以阅读有关 Regular Expressions on JavaScript here
的更多信息实现 shouldShowNavBar
的另一种方法是使用一些数组谓词,例如 some
:像这样:
shouldShowNavBar(url: string): boolean {
const conditions = [
!url.startsWith('/admin/dashboard'),!url.includes('/admin/category'),// More conditions?
];
return conditions.some(isTrue => isTrue);
}
如果您不想使用异步,请按原样保留代码:
<div class="main__container">
<app-navbar *ngIf="shouldDisplayNavBar(url)">
</app-navbar>
<app-footer *ngIf="shouldDisplayNavBar(url)">
</app-footer>
</div>
shouldShowNavBar(url: string): boolean {
if(!url) {
return false;
}
const conditions = [
!url.startsWith('/admin/dashboard'),// More conditions?
];
return conditions.some(isTrue => isTrue);
}