【问题标题】:Angular reference id in ngClass best practicesngClass 最佳实践中的角度参考 id
【发布时间】:2020-02-21 06:46:16
【问题描述】:

我编写此代码是为了在活动页面更改时更改导航栏选项的 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. 如果我手动更改地址,此代码将失败并将主页显示为活动页面,因为它是默认页面 - 我该如何解决这个问题?

【问题讨论】:

  • 1. &lt;li&gt; 标签的id 属性? 2. 如果页面地址被手动更改,您期望会发生什么?
  • 比这更好的方法,它不是基于 id 而是 /someAdress 这里是基于或什么是更好的做法

标签: angular ng-class


【解决方案1】:

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;
    });
  }
}

您可以查看它是如何工作的here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 2014-03-06
    • 2017-04-06
    • 1970-01-01
    相关资源
    最近更新 更多