我有这个简单的*ngfor
<button ion-button *ngFor="let markerColor of markerColors, let i = $index" (click)="markText()" [disabled]="status.pdf.pagesLoaded == 0" class="$markerColor.className">
<ion-icon name="md-brush">{{markerColor.className}}</ion-icon>
</button>
它正确地渲染到
<button class="someClass disable-hover button button-ios button-default button-default-ios" ion-button=""><span class="button-inner">
<ion-icon name="md-brush" role="img" class="icon icon-ios ion-md-brush" aria-label="brush" ng-reflect-name="md-brush">marker-color-1</ion-icon>
</span><div class="button-effect"></div>
</button>
我在我尝试过的班级中渲染{{markerColor.className}}
:
class="markerColor.className"
获取
class="markerColor.className disable-hover button button-ios button-default button-default-ios"
如果A使用属性[class]="markerColor.className"
或class="{{markerColor.className}}"
,则呈现名称,但其他类丢失。class="marker-color-1
如何正确地将类添加到此NGFOR?
谢谢
您应该使用ngclass,因为它不会覆盖其他任何其他方法添加的类:
<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>
因此,在您的情况下,这将是这样的:
<button ion-button *ngFor="let markerColor of markerColors, let i = index" (click)="markText()" [disabled]="status.pdf.pagesLoaded == 0" [ngClass]="markerColor.className">
<ion-icon name="md-brush">{{markerColor.className}}</ion-icon>
</button>