ngClass最佳实践中的角参考ID

问题描述 投票:0回答:1

当活动页面更改时,我编写了此代码来更改导航栏选项的css。

html:

   <ul>
        <li routerLink="/" id="homePage" (click)="selected($event)"
            [ngClass]="{'default': activePage=='homePage', 'active': activePage!=='homePage' }">Home
        </li>

        <li id="placeholder" routerLink="/placeholder" (click)="selected($event)"
            [ngClass]="{'default': activePage=='placeholder', 'active':  activePage!=='placeholder' }">PlaceHolder
        </li>
    </ul>

TS:

  public selected($event) {
    var target = event.target || event.srcElement || event.currentTarget;
    this.activePage = target["id"];
  }

但是我有两个我不知道的问题:

  1. 我希望能够编写[ngClass]来检查id属性,而不仅仅是将id作为硬编码的字符串

  2. 如果我手动更改地址,此代码将失败,并将主页显示为活动页面,因为它是默认页面-我该如何解决?

angular ng-class
1个回答
0
投票

Router将帮助您实现预期的行为。

<ul>
  <li [routerLink]="routes.home"
      [ngClass]="{ 'activated': currentTab === routes.home}">
    Home
  </li>
  <li [routerLink]="routes.placeholder"
      [ngClass]="{ 'activated': currentTab === routes.placeholder}">
    PlaceHolder
  </li>
</ul>
<router-outlet></router-outlet>
import { Component } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter, map } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {

  currentTab = '';

  readonly routes = {
    home: '/home',
    placeholder: '/placeholder'
  };

  constructor(private router: Router) {
    this.router.events
      .pipe(
        filter(e => e instanceof NavigationEnd),
        map((e: NavigationEnd) => e.url)
      )
      .subscribe(newUrl => {
        this.currentTab = newUrl;
    });
  }
}

UPDATE

Location服务的使用已删除,因为路由器的事件包含有关当前URL的信息

© www.soinside.com 2019 - 2024. All rights reserved.