【问题标题】:Can't get reactive form validations to work using FormArray无法使用 FormArray 进行反应式表单验证
【发布时间】:2019-12-05 00:31:40
【问题描述】:

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

在添加 FormGroups 数组之前它正在工作(材料步进器验证目的)。

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]] }),
    ])
});

我做错了什么?

【问题讨论】:

  • 这看起来很奇怪......通常当我们有一个表单数组时,它包含具有相同表单控件的表单组。为什么需要 formarray 和嵌套的 formgroups?为什么不只是表单控件?
  • 这样我就可以使用线性角度的材料步进器而无需创建额外的 FormGroups

标签: angular angular-reactive-forms formarray formgroups


【解决方案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 控件索引。我完全不确定您为什么需要或想要这种结构,但现在可以使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 2017-12-30
    • 2019-05-04
    相关资源
    最近更新 更多