如何根据哪个路由器链接处于活动状态来编写条件代码

时间:2017-11-30 11:24:09

标签: angular angular-directive angular-router

我的尝试是这样的:

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

2 个答案:

答案 0 :(得分:3)

您可以创建自己的结构指令,类似于NgIf,如果您的活动路由与传递给指令的路径匹配,您将在DOM中传递路径并呈现内容,如下所示:

如果-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>

答案 1 :(得分:0)

@ stefan-svrkota的答案很棒,但我发现*ngIf="router.url=='/login'"也有效