Angular:带有 *ngClass 的条件类

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

What is wrong with my Angular code? I am getting the following error:

无法读取 BrowserDomAdapter.removeClass 中未定义的属性删除"

Cannot read property 'remove' of undefined at BrowserDomAdapter.removeClass

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

推荐答案

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

Angular version 2+ provides several ways to add classes conditionally:

键入一个

[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'"

相关文章