user6701863 user6701863 - 2 months ago 5x
AngularJS Question

Angular 2 - How do I write an ngIf that checks if I have already added something to my cart?

I have a list of albums, which I am using to render out the albums on the page.

The list is just an array of album objects, one of the properties of the object is ID.

When I add an album to my cart, I add that album object to my cart array.

How can I write my ngIf when I am keeping track of two different arrays?

So here's an example how I render the album on the page:

<h4 class="album-title">{{album.title}}</h4>
<p class="album-info-artist">{{album.artist}}</p>
<button class="btn btn-sm" (click)="add(album)">Add</button>

If I want to change the button text from Add to Remove, once I add an album, how can I write that ngIf? Or is there a better way to do it? I need to keep a track of the from the album array, and I need to track the when I add the album to cart.

I know how to do this in reactJS, but I am new to ng2 and not sure how to accomplish this.


In your component:

isAlbumInCart(album) {
    return cart.indexOf(album) >= 0;

In your view

<button *ngIf="!isAlbumInCart(album)" class="btn btn-sm" (click)="add(album)">Add</button>
<button *ngIf="isAlbumInCart(album)" class="btn btn-sm" (click)="remove(album)">Remove</button>

Of course, is the array is very large, this is not very fast. You could just add a flag to the album when adding it to the cart, and check this flag.