以角度5获取动态输入类型的值

时间:2018-04-06 11:10:13

标签: angular dom

我正在运行一个问题,我需要在点击Add时创建动态输入行。我使用索引将我的模型与元素绑定,并且它的工作正常。

<div class="row" *ngFor="let field of fieldArray; let i = index">
  <div class="col-sm-2 form-group">
    <label for="grid-input-19">Service Name</label>
      <select class="form-control" name="Service-{{i}}" [(ngModel)]="field.selectedService" #Service="ngModel" (ngModelChange)="onChange($event)">
          <option *ngFor="let service of serviceList" [selected]="service.Service == field.selectedService"
                  [ngValue]="service">
            {{service.Service}}
          </option>
        </select>
      </div>
      <div class="col-sm-4 form-group">
        <div class="form-group">
          <label for="grid-input-18">Service Description</label>
          <textarea rows="1" name="Description-{{i}}" [(ngModel)]="field.selectedService.Description" required
                    class="form-control" [readonly]="true"></textarea>
        </div>
      </div>
      <div class="col-sm-1 form-group">
        <label>Quantity</label>
        <input type="number" min="1" value="1" step="any" name="Quantity-{{i}}" id="daterange-5" [(ngModel)]="field.selectedService.Quantity" required
               maxlength="50" class="form-control" (blur)="onQuantityChange($event.target.value)">
      </div>
      <div class="col-sm-2 form-group">
        <label>Price</label>
        <input type="number" min="0" value="0" step="any" name="Price-{{i}}" id="daterange-5" [(ngModel)]="field.selectedService.Price" required
               maxlength="50" class="form-control" [readonly]="true">
      </div>
    </div>
</div>

问题是Quantity更改我正在调用一个需要修改价格的函数。但是每一行输入的数量都在一起变化。假设有三行输入。所以改变第一行输入的Quantity。所有人都在一起偏转。我做错了什么。

onQuantityChange(quantity) {
    // How do I bind the value of row input price which is created dynamically on quantity change
    this.field.Price *= parseInt(quantity);
}

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

尝试为输入数量生成id&amp;使用ngFor的索引值唯一的价格就像你为名字所做的那样。

<input type="number" min="1" value="1" step="any" name="Quantity-{{i}}" id="quantity{{i}}">
<input type="number" min="1" value="1" step="any" name="price-{{i}}" id="price{{i}}">

一旦您拥有唯一ID,您就能识别数量和数量价格使用事件ID。

onQuantityChange(quantity,event) {
    this.fieldID = event.target.id.replace( /^\D+/g, '');  
              // output will be something like 0 for first quantity
              //then   get correcponding price element and multiply
    this.field.Price *= parseInt(quantity);  
}