Anna
Anna

Reputation: 1689

Angular:add dynamic class

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

Answers (3)

Pranay Rana
Pranay Rana

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

Karthic G
Karthic G

Reputation: 1182

Try this,

HTML:

<div *ngFor="let file of File">
 <span [style.border-color]="file.borderColor"></span>
</div>

Upvotes: 1

Pardeep Jain
Pardeep Jain

Reputation: 86730

It should be -

 <span [ngClass]='dynamicClass'></span>

working example

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>

Read more about ngClass here

Upvotes: 0

Related Questions