【问题标题】:how to get all values of input number field which is generated in *ngfor如何获取 *ngfor 中生成的输入数字字段的所有值
【发布时间】:2021-04-30 18:14:05
【问题描述】:

我有一个显示购物车产品的表格,在数量字段中,我可以选择让用户增加或减少数量,如果我在 for 循环中更新 btn,它会为每个提供单独的 btn,但我需要单个更新 btn在 for 循环之外获取输入字段的所有值..

 <tbody  *ngFor="let cartproducts of  cartpro.cartproducts ">

     <input id="number"   type="number" value="{{cartproducts.quantity}}" (change)="callMethod($event)"   class="updatequan"> </tbody>

更新btn:

  <button type="button"  class="btn btn-success"  (click)="updatecart($event)">Update cart </button>

组件.ts

    callMethod(e:any)
      {
    
    this.quantity=  e.target.value
    console.log("current quantity",this.quantity)
    
    }

 
  updatecart(e:any){
    console.log("udpate to",this.quantity)
  }

如果 updatebtn 在 forloop 之外,它正在工作,但它显示最近更改...但我需要将所有更改存储在 []

【问题讨论】:

    标签: html angular ngfor


    【解决方案1】:

    你需要看ReactiveFormsModule

    基本上你定义一个表单并使用.value属性你可以获得你需要的任何属性

    在你的组件文件中

      constructor(private fb: FormBbuilder) { }
       cartpro = this.fb.group({
        cartProducts this.fb.array([
        ])
      })
      get cartProducts() {
        return this.cartpro.get('cartProducts ') as FormArray
      }
      
    

    在你的 html 中

    <form [formGroup]='cartpro'>
      <tbody formArrayName='cartProducts'>
        <tr *ngFor="let cartproduct of cartProducts" [formGroupName]='i'>
          <input id="number" type="number" formControlName='quantity' class="updatequan"> 
        </tr>
    
      </tbody>
    </form>
    

    基本上你现在可以通过this.cartProducts.value访问产品的价值

    【讨论】:

    • 我会尽力回复你:)
    猜你喜欢
    • 1970-01-01
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    相关资源
    最近更新 更多