无法获得反应式表单验证以使用FormArray正常工作

时间:2019-07-26 16:23:05

标签: angular angular-reactive-forms formarray formgroups

我正在尝试使用一组FormGroups来验证我的表单。

在添加一个FormGroup数组之前,它一直在工作(重要的步进验证目的)。

HTML:

<form [formGroup]="formGroup" (ngSubmit)="submit()">
<mat-form-field>
    <input matInput formControlName="fullName" required>
    <mat-error *ngIf="formGroup.controls.formArray.controls['fullName'].errors?.required">Required</mat-error>
</mat-form-field>

<mat-form-field>
    <input matInput formControlName="shortName" required>
    <mat-error *ngIf="formGroup.controls.formArray.controls['shortName'].errors?.required">Required</mat-error>
</mat-form-field>
</form>

TS:

get formArray(): AbstractControl | null { return this.formGroup.get('formArray'); }

this.formGroup = this.fb.group({
    formArray: this.fb.array([
        this.fb.group({ fullName: [null, [Validators.required]] }),
        this.fb.group({ shortName: [null, [Validators.required]] }),
    ])
});

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

这里的数组是一个组数组,您需要这样对待,顺便说一句,这是一种奇怪的方式...

<form [formGroup]="formGroup" (ngSubmit)="submit()">
  <ng-container formArrayName="formArray">
    <mat-form-field formGroupName="1">
        <input matInput formControlName="fullName" required>
        <mat-error *ngIf="formGroup.controls.formArray.controls[1].controls['fullName'].errors?.required">Required</mat-error>
    </mat-form-field>

    <mat-form-field formGroupName="2">
        <input matInput formControlName="shortName" required>
        <mat-error *ngIf="formGroup.controls.formArray.controls[2].controls['shortName'].errors?.required">Required</mat-error>
    </mat-form-field>
  </ng-container>
</form>

所以我添加的是一个容器,该容器引用表单数组名称,然后使用指令让它知道该数组中每个控件的formGroupName(在FormArray的情况下为索引)。我还在验证检查中添加了一个步骤,可以在其中访问formarray控件索引。我完全不确定为什么需要或想要这种结构,但是现在可以使用了。