Home > other >  Angular dynamic class using variable
Angular dynamic class using variable

Time:11-03

I have an enum that map a given keyword to a CSS class.

enum Colors {
 WHT = 'color--white'
}

and inside the component I created a new property with that value colors = Colors and I'm using it as it follows

 <p [ngClass]="[colors['WHT']]">My paragraph</p>

In this scenario it works as expected.

The problem is when I try to add a condition to this class binding.

 <p [ngClass]="{ [colors['WHT']]: false }> My paragraph </p>"

The official documentation doesn't provide any information about this use case, but it doesn't provide an example for <p [ngClass]="[componentColors['WHT']]"> My paragraph</p> either and this approach works fine.

Update: The false condition is just demo purposes, in the real scenario it will use a variable.

CodePudding user response:

Create proper json object in the component layer, then bind it

component:

  colors=Colors;
  yourStyles={ 
    'foo':false,
    'bar':true,
    [this.colors['WHT']]: true, 
  }

template:

<p [ngClass]="yourStyles">My paragraph</p>

result:

<p _ngcontent-wma-c40=""  ng-reflect-ng->My paragraph</p>

https://stackblitz.com/edit/angular-roatih?file=src/app/app.component.html

obviously yourStyles has to reflect requested conitions to enable/disable given class.

CodePudding user response:

Found the solution in the following:

<p [ngClass]="true ? colors['WHT']:''"> My Paragraph </p>

Where true is the condition (property).

  • Related