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>
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.
Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.
'css-class-1' : 'css-class-2' . So ngClass still can use ternary operator in Angular 2.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With