1

I have a condition in my html template that loops through an object and create a list of items. I have studied [NgClass] because I need to set the class of a row based on a condition of that particular item. So my understanding and testing shows that NgClass is set once based on a variable. I want it to check during every loop if true/false. So basically I want <div [ngClass]="{'redclass': {{hour.enoughrest}}}"> However this of course do not work. Any ideas? I have feeling the solution is obvious but I am at loss.

5
  • So you want to apply a certain classes based on something only if a 'something else' is true? Commented May 10, 2019 at 9:10
  • Remove interpolation from {{hour.enoughrest}} Commented May 10, 2019 at 9:15
  • <div [ngClass]="{'redclass': hour.enoughrest}"> Commented May 10, 2019 at 9:23
  • correct but it is different for of course everytime the loop executes Commented May 10, 2019 at 9:29
  • Thank you so much!! I understand now and it works perfectly Commented May 10, 2019 at 9:32

4 Answers 4

2

Use this format:

 [ngClass]="{'yourClassName': condition}"
Sign up to request clarification or add additional context in comments.

Comments

1

It is definitely possible with ngClass. See if example helps.

e<ng-template ngFor let-item [ngForOf]="folios">
    <tr *ngIf="item.shares >0" [ngClass]="{'table-success': item.gainPercent >5,'table-danger': item.gainPercent <-5}">e

Comments

0

If you want to apply the class based on a condition, then try this:

<div [class.redclass]="hour.enoughrest">
</div

Comments

0

There are several ways to change class dynamically.

<div [ngClass]="{'redclass': hour.enoughrest}">

Or

[class.redclass]="hour.enoughrest"

Or if you want to add class based on condition

<div [className]="condition ? 'example-class' : 'other-class'"></div>

In addition to that you can change NgStyle dynamically and update style as bellow if you want to do style changes.

<p [ngStyle] = “{backgroundColor : getColor() }” >

in .ts file
getColor() {
  return this.serverStatus === ‘online’? ‘green’: ‘red’;
}

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.