how to use [ngClass] for multiple class conditions Angular4

Viewed 15090

currently my div looks like this:

<div class="class-a" [ngClass]="{'class-b': !person.something}">

now I want to have another condition...

so now I want this div to be of class-a If something class-b If something else class-c

how should I do this?

im using angular 4.

thanks!

3 Answers

Add it like properties to an object literal:

[ngClass]="{'class-b': !person.something, 'other-condition': isOther }"

Another option is to return a string from the component if you think you need more complex logic, or know there will only be one. This might be more testable.

Whatever string you return will be rendered as a class(es)

[ngClass]="renderClass()"

renderClass() {
  switch(this.user.theme){
    case "dark":
       return "dark-theme"
    case "light":
       return "light-theme"
  }
}

The better way for use this Syntax ngStyle Because, it's Not Completed Answer.

If you want to toggle some classes like text-info Or text-danger for <i> tag (

some exp ? 'text-info' : 'text-danger'

).

The best answer is array not object.

[ngClass] = "[some exp ? 'text-info' : 'text-danger', ...]"

GoodLuck

Related