0

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>

1
  • is that worked for you ? Commented May 9, 2018 at 16:38

3 Answers 3

1

Try this,

HTML:

<div *ngFor="let file of File">
 <span [style.border-color]="file.borderColor"></span>
</div>
Sign up to request clarification or add additional context in comments.

Comments

0

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

4 Comments

This did not worked in my case, the comment below worked
@Anna have you checked my working example? and comment below is adding style dynamically not class. I think question is about adding class dynamically
Yes i check you working ex, same code did not work in my workspace
@Anna then most probably error is somewhere else from your code, please check that !
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.