如果满足条件则停止div上的click事件-Angular 5 [英] Stopping a click event on a div if a condition is met -- Angular 5

查看:226
本文介绍了如果满足条件则停止div上的click事件-Angular 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个循环,它产生了20格。每个div是我的本地对象数组中的一个对象。这是代码:

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>

当用户单击div(item)时,它将添加到数组中:

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;
  }

在任何情况下,用户都不允许在数组中添加同一项两次,但我不想更改 userInventory 数组(或 splice()它)。我希望它仍然可见,只需更改它的某些样式,使其看起来已禁用。您还可以看到,单击该项目时, item.i☎联系人变为 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.

我要做的是,当item.i⚓为true时,禁用div上的(单击)事件侦听器(并添加一些样式),因此即使多次单击,用户也无法添加相同的项目。

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.

推荐答案

为此,您可以为购物车中添加的每个项目添加一个类。如下:

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>

然后,在 .ts 组件文件中,请添加以下条件:

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
    }
}

希望有帮助! :)

这篇关于如果满足条件则停止div上的click事件-Angular 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆