angularng-class

Angular: NgClass - Grouping conditions


Is there a way to simplify this ngClass?

The below works, but it feels like it could be streamlined.

<div [ngClass]="[
 edit ? 'class-1' : 'class-2',
 value === 'value1' && released ? '' : 'class-3',
 value === 'value2' ? 'class-3' : ''
]">

Solution

  • You can optimise a part of it by moving to [class], much shorter and concise:

    <div [class.class-3]="(value === 'value1' && !released) || value === 'value2'"
    ... /the rest of the ngClass for edit
    </div>
    

    or keep it all in ngClasse. It can be also shorter:

    <div [ngClass]="[
     edit ? 'class-1' : 'class-2',
     released ? value != 'value1' || value==='value2'? : 'class-3' : ''
    ]">