gpt4 book ai didi

angular - 如何根据激活的路由器链接编写条件代码

转载 作者:太空狗 更新时间:2023-10-29 18:24:40 26 4
gpt4 key购买 nike

我的尝试是这样的:

<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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com