我如何使用反应形式将formArray嵌套在另一个formArray中

时间:2019-09-14 04:58:08

标签: angular

我有一个使用数组的反应形式,并具有以下结构:

 this.myForm = this.fb.group({
  names: this.fb.array([
    this.fb.group({ element_name: [null, [Validators.required]] }),
    this.fb.group({ element_name: [null, [Validators.required]] }),
  ])

enter image description here

一切正常,执行相应的验证。

我想在另一个文本字段中添加lastname并进行所需的验证,但是我不知道如何容纳图像中的内容:

enter image description here

我尝试做类似"names"的事情,但这并没有出错。我能做什么?

这是我的实时代码:

https://stackblitz.com/edit/angular-nm2vah?file=app/app.component.html

这是我的代码:

<form [formGroup]="myForm">
  <div formArrayName="names">
      <ng-container
          *ngFor="let item of myForm.get('names').controls; let i=index">
          <div [formGroupName]="i">
                  name <input type="text" class="form-control" id="element_name"
                      formControlName="element_name"
                      placeholder="insert name" 
                  >
                  <!--lastname 
                  <input type="text" class="form-control" id="element_lastname"
                      formControlName="element_lastname"
                      placeholder="insert last name" 
                  >-->
          </div>
      </ng-container>
  </div>
</form>


this.myForm = this.fb.group({
  names: this.fb.array([
    this.fb.group({ element_name: [null, [Validators.required]] }),
    this.fb.group({ element_name: [null, [Validators.required]] }),
  ]),
  lastname: this.fb.array([
    this.fb.group({ element_name: [null, [Validators.required]] }),
    this.fb.group({ element_name: [null, [Validators.required]] }),
  ])

})

1 个答案:

答案 0 :(得分:2)

您需要在姓氏名称的相同表单组中添加姓氏。

this.myForm = this.fb.group({
  names: this.fb.array([
    this.fb.group({
      element_name: [null, [Validators.required]],
      element_lastname: [null, [Validators.required]]
    }),
    this.fb.group({
      element_name: [null, [Validators.required]],
      element_lastname: [null, [Validators.required]]
    }),
  ]),
})

您的HTML:

<form [formGroup]="myForm">
  <div formArrayName="names">
      <ng-container
          *ngFor="let item of myForm.get('names').controls; let i=index">
          <div [formGroupName]="i">
                  name <input type="text" class="form-control" id="element_name"
                      formControlName="element_name"
                      placeholder="insert name" 
                  >

                  <input type="text" class="form-control" id="element_lastname"
                      formControlName="element_lastname"
                      placeholder="insert last name" 
                  >
          </div>
      </ng-container>
  </div>
</form>