Angular 2 ngClass conditional with data?

18,133

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.

Share:
18,133

Related videos on Youtube

Kenzo
Author by

Kenzo

Updated on June 04, 2022

Comments

  • Kenzo
    Kenzo almost 2 years

    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>
    
  • Kenzo
    Kenzo over 6 years
    Great that works. But I have 2 for loops and perk.perk will not register in the location I want to place it. How can I reference it?
  • LLai
    LLai over 6 years
    @Kenzo so perk and perkResult are in different scopes. I would suggest storing perk.perk in another variable. (say when something is selected). Then you can compare perkResult.perk === newVar
  • Alberto
    Alberto over 5 years
    This solution will produce a compile error, because you can't use both [] square bracket operator and {{}} interpolation operator. A valid solution is here: stackoverflow.com/questions/35269179/…