0

I want to make buttons whose color and border color are set as independent variables in the component controller. The documentation and these answers show how to do multiple static classes but not multiple dynamic classes. I tried a few ways but these didn't work:

[ngClass]="[color] [border]" // doesn't work

[ngClass]="[color], [border]" // doesn't work

[ngClass]="[color, border]" // not dynamic binding

[ngClass]="{[iClass]: true, [iBorder]: true,}" // doesn't work

Maybe I should use one dynamic class with in the view and spin up the CSS properties into a class on the fly in the component controller?

Thomas David Kehoe
  • 10,040
  • 14
  • 61
  • 100

2 Answers2

2

Try this:

<div [ngClass]="{'class1': expression1, 'class2': expression2}"></div>
Zrelli Majdi
  • 1,204
  • 2
  • 11
  • 16
1

Usually I put the logic in the controller but with ngClass the logic should be in the view. This eliminates the need for dynamic classes.

[ngClass]="{ 
   green: l2Language === 'English', 
   gray: l2Language === 'Spanish',
   red: l2Language === 'Chinese',
   finnishBlue: l2Language === 'Finnish',
   blackBorder: l1Language === 'English' || 'Spanish',
   width180: l1Language === 'English' || 'Spanish'
}"

This puts multiple classes (color, border, width) on a single button, controlled by multiple variables (languages). When the language is English the button is green with a black border and a width of 180 pixels. When the language is Chinese the button is red with no border and no set width.

Thomas David Kehoe
  • 10,040
  • 14
  • 61
  • 100