Search code examples
javascriptangularng-class

Angular2 [ngClass] - Combining direct binding with conditional classes


I currently have two different working implementations of [ngClass] on an element;

[ngClass]="{ selected: element.isSelected, highlighted: element.isHighlighted}"

and

[ngClass]="element.customClasses"

Is it possible to combine both of these approaches in the template, or do I have to create a method in my component to return an array of classes based on the logic above?

Thanks!


Solution

  • I opted for using [class.*] to set the conditional classes, leaving [ngClass] to handle the binding;

    <div 
      [ngClass]="element.customClasses" 
      [class.selected]="element.isSelected"
      [class.highlighted]="element.isHighlighted"
    ></div>