角度:带有 *ngClass 的条件类

我的 Angular 代码有什么问题?我收到以下错误:

无法在 BrowserDomAdapter.removeClass 上读取 undefined 的属性“remove”

<ol>
  <li *ngClass="{active: step==='step1'}" (click)="step='step1'">Step1</li>
  <li *ngClass="{active: step==='step2'}" (click)="step='step2'">Step2</li>
  <li *ngClass="{active: step==='step3'}" (click)="step='step3'">Step3</li>
</ol>

答案 1

Angular 版本 2+ 提供了几种有条件地添加类的方法:

类型一

    [class.my_class] = "step === 'step1'"

类型二

    [ngClass]="{'my_class': step === 'step1'}"

和多个选项:

    [ngClass]="{'my_class': step === 'step1', 'my_class2' : step === 'step2' }"

类型三

    [ngClass]="{1 : 'my_class1', 2 : 'my_class2', 3 : 'my_class4'}[step]"

类型四

    [ngClass]="step == 'step1' ? 'my_class1' : 'my_class2'"

您可以在文档页面上找到这些示例


答案 2

[ngClass]=...而不是。*ngClass

*仅用于结构指令的速记语法,例如,您可以使用

<div *ngFor="let item of items">{{item}}</div>

而不是更长的等效版本

<template ngFor let-item [ngForOf]="items">
  <div>{{item}}</div>
</template>

另请参见 https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html

<some-element [ngClass]="'first second'">...</some-element>
<some-element [ngClass]="['first', 'second']">...</some-element>
<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>
<some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>
<some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>

另请参见 https://angular.io/docs/ts/latest/guide/template-syntax.html

<!-- toggle the "special" class on/off with a property -->
<div [class.special]="isSpecial">The class binding is special</div>

<!-- binding to `class.special` trumps the class attribute -->
<div class="special"
     [class.special]="!isSpecial">This one is not so special</div>
<!-- reset/override all class names with a binding  -->
<div class="bad curly special"
     [class]="badCurly">Bad curly</div>