1

Is there any way in angular, html or css to dynamically apply CSS based on object value:

HTML:

<mat-grid-tile *ngFor="let obj of objs">    
 <span class="(value according to variable)">
   {{ obj.n }}
 </span>
</mat-grid-tile>

CSS:

.first {
  color: #db4437;
}

.second {
  color: #32cd32;
}

What I want to do is, if obj.n is red, I want first as the class of span tag and second => otherwise

2 Answers 2

2

Try [ngClass] and evaluate expression

<mat-grid-tile *ngFor="let obj of objs">    
  <span [ngClass]="(obj.n ==='red')? 'first' : 'second'">
  {{ obj.n }}
  </span>
</mat-grid-tile>

Take a look at this demo

Sign up to request clarification or add additional context in comments.

3 Comments

It is not working, Unexpected character "EOF" (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.) I think there is some mistake in span tag ending with ".
@HarshilShah : The answer you have selected is crude and has redundant code of [class.first] and [class.second]. Not a recommended angular way. Upto you. :)
I have different classes for different type of values of the obj. That's why I'm choosing another answer. Otherwise yours is working just fine, too.
1

Or

<span [class.first]="obj.n === 'red'" [class.second]="obj.n !== 'red'">{{obj.n}}</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.