作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我的尝试是这样的:
<ul class="nav nav-tabs search-selector" role="tablist">
<li routerLinkActive="active"
[routerLinkActiveOptions]="{ exact: true }">
<a routerLink="{{ myroute[0].link }}">{{ myroute[0].label }}</a>
</li>
<li routerLinkActive="active"
[routerLinkActiveOptions]="{ exact: true }">
<a routerLink="{{ myroute[1].link }}">{{ myroute[1].label }}</a>
</li>
</ul>
<div *ngif="route0 is active">do something related to route 0</div>
<div *ngif="route1 is active">do something related to route 1</div>
最佳答案
您可以创建自己的结构指令,类似于 NgIf
,如果您的事件路由与您传递给指令的路由匹配,您将在其中传递路由并在 DOM 中呈现某些内容,如下所示:
if-route.directive.ts
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
@Directive({ selector: '[ifRoute]' })
export class IfRouteDirective {
private hasView = false;
private subscription: Subscription;
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private router: Router) { }
@Input() set ifRoute(route: string) {
this.performCheck(route);
this.subscription = this.router.events.subscribe(
res => {
this.performCheck(route);
}
)
}
performCheck(route) {
if (route === this.router.url && !this.hasView) {
this.viewContainer.createEmbeddedView(this.templateRef);
this.hasView = true;
} else if (route !== this.router.url && this.hasView) {
this.viewContainer.clear();
this.hasView = false;
};
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
您可以在模板中像这样使用它:
<p *ifRoute="'/login'">
This will be displayed only if you are on login route.
</p>
关于angular - 如何根据激活的路由器链接编写条件代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47572286/
我是一名优秀的程序员,十分优秀!