Reputation: 1689
I have a json that will return me border color, which is to be applied to a span. JSON is File = [ { 'borderColor':'red' } ]
How to apply class dynamically?
My html is, simple
<div *ngFor="let file of File">
<span dynamicClassComesHere></span>
Upvotes: 0
Views: 120
Reputation: 176896
as its just single style use ngStyle
like this
const style = {'borderColor':'red'};//ts file
<span [ngStyle]="style"></span >
<span [ngStyle]="{'borderColor':getBorderColor()}"></span >
in your case
<div *ngFor="let file of File">
<span [ngStyle]="JSON.stringify(file)"></span>
or can be like this
<span [style.borderColor]="getBorderColor()">
getBorderColor() {
style = JSON.parse(`{ 'borderColor':'red' }`);
return style.borderColor;
}
in your case
<div *ngFor="let file of File">
<span [style.borderColor]="file.borderColor"></span>
Upvotes: 0
Reputation: 1182
Try this,
HTML:
<div *ngFor="let file of File">
<span [style.border-color]="file.borderColor"></span>
</div>
Upvotes: 1
Reputation: 86730
It should be -
<span [ngClass]='dynamicClass'></span>
Apart from this there are various ways to do so as per official docs
<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>
Upvotes: 0