使用动态表单,我需要使用户能够动态创建表单字段。需要有一个“添加”按钮,当用户单击该按钮时,将创建4个输入字段。

到目前为止,我已经能够动态创建一个字段。下面是我的代码

在HTML中,我正在使用索引来创建formControlName

<div class="row">
          <div class="col-xs-12">
            <div formArrayName="properties">

              <button class="btn btn-default btn-xs" type="button" (click)="onAddProperty()">Add</button>
              <div class="form-group" *ngFor="let propertyControl of searchForm.get('properties').controls; let i = index">
                <input type="text" class="form-control" [formControlName]="i">

                <!--       <input type="text" class="form-control" [formControlName]="'B'"+"i">
              <input type="text" class="form-control" [formControlName]="'C'"+"i">
              <input type="text" class="form-control" [formControlName]="'D'"+"i"> -->
              </div>
            </div>
          </div>
        </div>

然后在组件中,将控件推到FormArray
searchForm: FormGroup;
onAddProperty() {
    const control = new FormControl(null);
    (<FormArray>this.searchForm.get('properties')).push(control);
  }

现在,我可以多次单击“添加”按钮,并且每次单击都会创建一个输入字段。

但是,我需要为每个单击创建4个输入字段,而不是一个输入字段。我不知道如何为每个表单字段赋予唯一的formControlName。现在,我正在使用该字段的索引,该索引对于1个字段是唯一的,但对于4个字段则不是。

最佳答案

我认为一个简单的for循环就可以在这里完成。至于您的模板,我在理解注释(在模板中)中的代码时遇到了一些麻烦。在这种情况下,除了在formArray的迭代中用索引声明formControlName之外,您无需执行其他任何操作,因此如下所示:

<div formArrayName="properties">
  <div *ngFor="let prop of searchForm.get('properties').controls; let i=index">
    <input type="text" class="form-control" [formControlName]="i">
  </div>
</div>

然后插入4个新输入字段的循环:

onAddProperty() {
  for(var i=1; i<=4; i++) {
    <FormArray>this.searchForm.get('properties').push(new FormControl());
  }
}

DEMO

09-16 17:18
查看更多