角度:通过动态循环输入设置反应形式

时间:2019-11-25 15:19:52

标签: javascript angular typescript angular-reactive-forms angular-forms

我必须为通过数据循环进行输入的表单设置反应性表单验证:

我的表单生成器如下所示:

constructor(private formBuilder: FormBuilder) { 
    this.userForm = this.formBuilder.group({
      'inputOne': ['', [Validators.required]],
      'inputOne': ['', [Validators.required]],
       ...
      'inputN': ['', [Validators.required]]
    });
  }

,我的模板如下所示:

<form [formGroup]="userForm">
  <div class="form-group" *ngFor="let item of items; let i=index;">
        <label for="lastName">{{item.name}}</label>
        <input class="form-control" name="lastName" id="lastName" type="text" [formControlName]="item.name">
      </div>
</form>

从我的后端动态加载项目的地方

如何以Angular反应形式动态填充控件?

1 个答案:

答案 0 :(得分:0)

听起来像是您想要一个表单数组,而不是一组...

  constructor(private formBuilder: FormBuilder) { 
    // build an empty form array
    this.userForm = this.formBuilder.array([]); 
  }

  // call this whenever you need to add an item to your array
  private addItem(item) {
    // build your control with whatever validators / value
    const fc = this.formBuilder.control(i.lastName, [Validators.required]);
    this.userForm.push(fc); // push the control to the form
  }

  // call this function whenever you need to reset your array
  private resetFormArray(items) {
    this.userForm.clear(); // clear the array
    items.forEach(i => this.addItem(i)); // add the items
  }

<form [formGroup]="userForm">
  <div class="form-group" *ngFor="let item of items; let i=index;">
    <label for="lastName">{{item.name}}</label>
    <input class="form-control" name="lastName" id="lastName" type="text" [formControlName]="i">
  </div>
</form>

请注意,您在此处使用索引作为表单控件名称