Stopping a click event on a div if a condition is met — Angular 5

半腔热情 提交于 2020-07-09 16:08:12

问题


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?


回答1:


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! :)




回答2:


try it with a condition:

(click)="!item.isAdded && addItemToArray(item)"



回答3:


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.




回答4:


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>


来源:https://stackoverflow.com/questions/49237514/stopping-a-click-event-on-a-div-if-a-condition-is-met-angular-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!