Home > Back-end >  Angular: NgClass - Grouping conditions
Angular: NgClass - Grouping conditions

Time:06-29

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

CodePudding user response:

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

CodePudding user response:

You really have a complex condition out there, this is the best I can think of:

<div
  [ngClass]="{
    'class-1': edit,
    'class-2': !edit,
    'class-3': value === 'value2' || (value === 'value1' && !released)
  }"
></div>
  • Related