I am new to Angular and I am building a website with a wishlist for each item (star font awesome icon). My trouble is I am unable to understand how to use ngStyle to fill the icon color with yellow when a user wishes to add the item to their wishlist (when the click event happens).
This is a par of my HTML code with the click event:
<div id="wishlist" (click)="addToWishList(item)"><i class="fa fa-star-o fa-2x" aria-hidden="true"></i></div>
The addToWishList(item) function is defined in my component and is working as expected. I did try to provide the color in ngStyles attribute in <div> however, it sets the color beforehand rather than on the click event.
Any help will be greatly appreciated. Thanks!
Using ngStyle:
<i
class="fa fa-star-o fa-2x"
aria-hidden="true"
[ngStyle]="{ color: THE_CONDITION_YOU_HAVE ? YOUR_NEEDED_COLOR : '' }"
></i>
Using [style.color]:
<i
class="fa fa-star-o fa-2x"
aria-hidden="true"
[style.color]="THE_CONDITION_YOU_HAVE ? YOUR_NEEDED_COLOR : ''"
></i>
Note that nowadays, Angular team recommends you to use style bindings rather than NgStyle as per documented here:
The NgStyle directive can be used as an alternative to direct [style] bindings. However, using the preceding style binding syntax without NgStyle is preferred because due to improvements in style binding in Angular, NgStyle no longer provides significant value, and might eventually be removed in the future.
So if you have this item you are displaying as an object, and is predefined with an interface or a class somewhere, you can go ahead to your item interface/class and add a parameter (Say for example you call it selected)
Now in your template you have to make the following adjustment
<div id="wishlist" (click)="addToWishList(item)">
<i [ngStyle]="{ color: item.selected ? yourColor : '' }" class="fa fa-star-o fa-2x" aria-hidden="true"></i>
</div>
The addToWishList() function would go something like this
addToWishList(item: Item) {
this.item.selected = !this.item.selected;
//Your code here
}
this would actually enable you to toggle the status of the item, so a click would add it to whishlist, another click would remove it from whishlist (As a style), and extra proccessing is required to remove it actually from the whishlist array.