Search code examples
angularng-class

Angular: NgClass - Grouping conditions


Is there a way to simplify this ngClass?

  • edit ? - This one works fine
  • value === - This is a child component. Each of the two parent components pass the value property down as an @Input. Child component 1 has a released property. Child component 2 does not have the released property.
  • If the value is value1 AND the released property is true, no class is added. However, if the released property is false add a class called class-3.
  • If the value is value2, always add class-3 as there is no released property.

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' : ''
    ]">