【问题标题】:Cannot read property 'target'无法读取属性“目标”
【发布时间】:2020-07-13 12:04:55
【问题描述】:

我正在尝试通过在循环中定位特定项目来增加价值。

<div *ngFor="let item of items; let i = index">
    <ion-button (click)="increment(i)">
      <ion-icon name="add"></ion-icon>
    </ion-button>
    <ion-input type="number" value="{{quantity}}"></ion-input>
</div>
    
    
    public items:Array<string> = []; //i
    public quantity:number = 0; //quantity

    increment(index:number){
     (this.quantity[index].target as HTMLInputElement).value[index] = this.quantity[index] + 1;
     console.log(this.quantity[index])
    }

【问题讨论】:

    标签: javascript reactjs angular typescript loops


    【解决方案1】:

    您的代码不完整,但正如我所见,您正试图从变量中访问一个类型为 number this.quantity 的元素。

    你应该访问变量items[index]

    如果你想单独存储每个项目的数量,我猜你 this.quantity 变量也应该是数组:

    public items:Array<string> = ['item1', 'item2', 'item3', 'item4']; //i
    public quantity:number[] = [0, 0, 0, 0]; //quantity
    
    increment(index:number){
     this.quantity[index] = this.quantity[index] + 1;
     console.log(this.quantity[index])
    }
    

    【讨论】:

    • 在单击项目 ngFor 循环(仅特定项目)内的按钮时增加输入类型编号的值在单击 increment(i) 事件后无论如何都会显示 NaN
    • 因此,如果您要使用 ngFor 打印项目,只需循环遍历所有项目并制作长度与 items 数量相同的数组并将它们设置为 0 或您需要的任何值。我将修改我的示例
    • 我更新了我的答案。这是否满足您的示例?如果没有,您可以添加更多代码以进行澄清
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    相关资源
    最近更新 更多