Reputation: 1905
I have a loop that generates let's say 20 divs. Each div is an object from my local objects array. Here's the code:
<div *ngFor="let item of userInventory"
class="col-2 c-pointer"
(click)="addItemToArray(item)">
<img src="{{item.image}}" class="img-fluid"/>
<span class="d-block">{{item.name}}</span>
</div>
When a user clicks on the div(item) it will add the item to an array:
addItemToArray(item) {
this.itemsToSend.push(item);
item.isAdded = true;
}
The user under no circumstances is allowed to add the same item twice in the array, but I do not want to mutate the userInventory
array (or splice()
it). I want it to still be visible, just change some styles on it so it looks disabled. Also as you can see, when the item is clicked, item.isAdded
becomes true
.
What I want to do is, when item.isAdded
is true, disable the (click) event listener on the div (and add some styles), so that the user cannot add the same item twice, despite clicking on it multiple times.
Is this doable in the current Angular implementation?
Upvotes: 4
Views: 10764
Reputation: 209
try it with a condition:
(click)="!item.isAdded && addItemToArray(item)"
Upvotes: 9
Reputation:
For the class, you can use this :
<div *ngFor="let item of userInventory" [class.disabled]="item.isAdded">
(I removed attributes for the sake of readability)
For the click, you can use a ternary :
<div *ngFor="let item of userInventory" (click)="item.isAdded ? null : addItemToArray(item)">
But the best solution would simply be to use a condition in your click handler I think.
Upvotes: 3
Reputation: 30739
You can simply use disabled
property to achieve this:
<div *ngFor="let item of userInventory"
class="col-2 c-pointer"
(click)="addItemToArray(item)"
[attr.disabled]="item.isAdded">
<img src="{{item.image}}" class="img-fluid"/>
<span class="d-block">{{item.name}}</span>
</div>
Upvotes: 1
Reputation: 2650
For that, you can add a class for each items which are added in the cart as below:
<div *ngFor="let item of userInventory"
class="col-2 c-pointer"
[class.disabled]="item.isAdded" <!-- Add this class, and customize its look -->
(click)="addItemToArray(item)">
<img src="{{item.image}}" class="img-fluid"/>
<span class="d-block">{{item.name}}</span>
</div>
Then, in your .ts
component file, add this condition:
addItemToArray(item) {
if (!item.isAdded) {
this.itemsToSend.push(item);
item.isAdded = true;
} else {
// add some error flash message
}
}
Hope it helps! :)
Upvotes: 6