【问题标题】:Angular 6 ngModel in ngFor doesn't workngFor 中的 Angular 6 ngModel 不起作用
【发布时间】:2019-01-06 15:41:04
【问题描述】:

我在 ngFor 循环中使用 ngModel 时遇到问题。我正在制作电子商务应用程序,我想通过数量获取输入值,但是每个 ngModel 都有相同的名称,因此它会不断更新所有输入,如下所示: Img 这是我的页面代码:

<div class="grid-container"> <!--  items  -->
    <div *ngFor="let item of items;" class="grid-item" >
      <img class="itemAv" src="{{item.imgUrl}}" width="100px" height="100px">
      <p>{{item.name}}</p>
      <p>${{item.price}}</p>
      <p>{{item.description}}</p>
      <div class="buy">
       <input class="quants" name="quants" type="number" min="0" max="100" [(ngModel)]="quants" placeholder = "1">
       <button class="buy" (click)="addToCart( item.name, item.price, quants , item.imgUrl )">buy</button>
      </div>
    </div>
有什么想法可以解决这个问题,或者如何添加动态 ngModel 名称,如“quant+item.id”?

【问题讨论】:

  • 您可以使用 ` 反引号或使用此模板变量文字:[(ngModel)]="quants{{ item.id }}"
  • 我得到一个错误,我不能在 ngModel 中使用插值:/
  • 您是否希望将您的quants 从文本框中分配给每个项目?

标签: javascript html angular


【解决方案1】:

向您的对象数组添加另一个属性,然后分配ngModel like,

 <input class="quants" name="quants" type="number" min="0" max="100" [(ngModel)]="item.quants" placeholder = "1">

【讨论】:

    【解决方案2】:

    尝试将item.quantity 添加到您的项目列表中,然后您可以这样做:

    <div class="grid-container"> <!--  items  -->
        <div *ngFor="let item of items;" class="grid-item" >
          <img class="itemAv" src="{{item.imgUrl}}" width="100px" height="100px">
          <p>{{item.name}}</p>
          <p>${{item.price}}</p>
          <p>{{item.description}}</p>
          <div class="buy">
           <input class="quants" name="quants" type="number" min="0" max="100" [(ngModel)]="item.quantity" placeholder = "1">
           <button class="buy" (click)="addToCart( item.name, item.price, item.quantity, item.imgUrl )">buy</button>
          </div>
        </div>
    

    【讨论】:

      猜你喜欢
      • 2018-11-09
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-15
      相关资源
      最近更新 更多