Angular 2 ngClass conditional with data?

Kenzo picture Kenzo · Jan 1, 2018 · Viewed 16k times · Source

So I am basically trying to set a highlight if an object is selected already. How can I compare the objects to change classes? Something like this

<[ngClass]="{{perkResult.perk === perk.perk}} ? 'highlight' : 'none-hightlight' ">

Current code:

<div class="col-xs-12">
  <div class="col-xs-12 benefit-selection">
     <ul class="benefits-dropdown-ul" *ngIf="perkList"> .     
      <a class="benefits-dropdown-div" *ngFor="let perkResult of perkList.results" (click)="onAddPerk(perkResult)">
       //highlight here
        <li class="benefits-dropdown-li">{{ perkResult.perk }}</li>
      </a>
     </ul>
  </div>
 </div>

 <div class="col-xs-6 benefit-selected" *ngFor="let perk of company.perks; trackBy: customTrackBy; let i = inde
    {{ perk.perk }}
 </div>

Answer

LLai picture LLai · Jan 2, 2018

You do not need the interpolation brackets {{}}. In this case, [ngClass] is looking for an expression, so

[ngClass]="perkResult.perk === perk.perk ? 'highlight' : 'none-hightlight'"

or

[ngClass]="[perkResult.perk === perk.perk ? 'highlight' : 'none-hightlight']"

will work.