Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 ngClass conditional with data?

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>
like image 503
Kenzo Avatar asked Jan 01 '18 22:01

Kenzo


People also ask

How do you write ngClass with condition?

To add a conditional class in Angular we can pass an object to ngClass where key is the class name and value is condition i.e., true or false as shown below. And in the above code, class name will be added only when the condition is true.

Can we use NgStyle and ngClass together?

Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.

Can we use ternary operator in ngClass?

'css-class-1' : 'css-class-2' . So ngClass still can use ternary operator in Angular 2.

What is the difference between ngClass and NgStyle?

The NgClass and NgStyle directives are used to apply style to the HTML element conditionally. The NgClass allows you to apply whole class based on condition whereas NgStyle gives you more flexibility to set individual properties.


1 Answers

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.

like image 59
LLai Avatar answered Oct 18 '22 18:10

LLai