输入字段必须单击几次以添加数字

时间:2019-05-20 14:09:10

标签: angular forms typescript angular-ngmodel

这是我的问题,我使用ngModelChange函数进行触发和事件。当我给出多个组时,它下面给出了多个输入字段。但是新的输入字段仅允许使用一个整数。如果要输入其他数字,则必须一次又一次单击输入字段。例如,如果我要输入100,则必须单击同一输入字段3次。

这是html部分

    <div class="row">
        <div class="col-md-12">
            <label>Number of Groups </label>
            <input type="number" name="numberofGroups" #numberofGroups="ngModel" [(ngModel)]="StudentCountservice.formData.numberofGroups" (ngModelChange)="onValueChange($event)"class="form-control" required>
        </div>
    </div>
    <div class="row" *ngFor="let grp of groups;let i=index " [attr.data-index]="i" >
        <div class="col-md-12">
            <label>Sizes of Group {{i+1}} </label>
            <input type="number" name="sizeofGroups" #sizeofGroups="ngModel" [(ngModel)]="groups[i]" class="form-control"ng-model-option="{debounce:750}"  required >
        </div>
    </div> 

这是ts文件代码部分

    onValueChange(newvalue){
    this.groups=[];
    for(var i=0;i<newvalue;i++){
      this.groups[i]=''; 
      }
    }

enter image description here

这是stackblitz示例

https://stackblitz.com/edit/angular-qfadvh

1 个答案:

答案 0 :(得分:1)

我找到了这个答案(https://github.com/angular/angular/issues/20589)。我将以下代码放入您的stackblitz中,它可以正常工作。尝试一下,让我知道是否无法正常使用。

这是我的闪电战叉子:https://stackblitz.com/edit/angular-sa8ww6

app.component.ts

// imports and metadata
export class AppComponent  {
  name = 'Angular';
  groups:any =[];

  onValueChange(newvalue){
    this.groups=[];
    for(var i=0;i<newvalue;i++){
      this.groups[i]=''; 
    }
  }

  // Add this function
  trackArray(index, item) {
    return index;
  }

}

app.component.html

trackBy: trackArray添加到了ngFor循环中

<div class="row">
  <div class="col-md-12">
    <label>Number of Groups </label>
    <input type="number" name="numberofGroups" #numberofGroups="ngModel" [(ngModel)]="test" (ngModelChange)="onValueChange($event)"class="form-control" required>
  </div>
</div>

<!-- add the trackBy: trackArray to this ngFor -->
<div class="row" *ngFor="let grp of groups;let i=index; trackBy: trackArray " [attr.data-index]="i" >
  <div class="col-md-12">
    <label>Sizes of Group {{i+1}} </label>
    <input type="number" name="sizeofGroups" #sizeofGroups="ngModel" [(ngModel)]="groups[i]" class="form-control"ngModelOptions="{updateOn: 'blur'}"  required >
  </div>
</div>