Search code examples
csssassng-class

ngClass one conditional and other from variable


I have the following data structure:

  this.filters = [
  {
    key: 'filter1',
    active: true,
    class: 'filter1Class'
  },
  {
    key: 'filter2',
    active: false,
    class: 'filter2Class'
  },
  {
    key: 'filter3',
    active: true,
    class: 'filter3Class'
  }
];

And with this I want to create some icons in my html, every icon will have each own css class and it can be enabled or not depending on the active flag in the model.

My classes are quite simples, every filterNClass is just a color and the one I applied to set it enabled or nor is an opacity value:

.disabled {
   opacity: 0.2;
}

.filter1Class {
   color: #1993a0;
}

.filter2Class {
   color: #720053;
}

.filter3Class {
   color: #000055;
}

this is my html:

<div *ngFor="let filter of filters">
  <mat-icon [ngClass]="filter.class"
            [ngClass]="{disabled: !filter.active}">alarm_on
  </mat-icon>
</div>

in this way, the second ngClass is not working, it does if I remove the first one, but I'm not able to manage both at the same time.

How can it be done?


Solution

  • I finally solved it by including a div:

    <div *ngFor="let filter of filters">
      <div [ngClass]="filter.class">
        <mat-icon 
            [ngClass]="{disabled: !filter.active}">alarm_on
        </mat-icon>
       </div>
    </div>