Angular 2 ngClass conditional with data?

浪子不回头ぞ 提交于 2019-12-12 14:43:21

问题


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>

回答1:


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.




回答2:


You want the whole expression inside {{}} to evaluate to the class string you want

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


来源:https://stackoverflow.com/questions/48053809/angular-2-ngclass-conditional-with-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!