协慌网

登录 贡献 社区

Angular:带 * ngClass 的条件类

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

无法读取 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 + 版本提供了几种有条件地添加类的方法:

第一类

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

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

另一种解决方案是使用[class.active]

例子 :

<ol class="breadcrumb">
    <li [class.active]="step=='step1'" (click)="step='step1'">Step1</li>
</ol>