首页 > 解决方案 > formArray里面的formGroup里面的验证控件

问题描述

如何验证 formGroup 中的控件,而该控件又位于数组中。

在这种情况下,我想验证numeroCelular

我有以下内容:

组件.ts

    this.formContacto = this.fb.group({
      telefonos: this.fb.array([
        this.fb.group({
          tipo: [''],
          numeroCelular: ['', Validators.required],
          whatsapp: [],
          codigoCiudad: [],
          numeroFijo: [],
        })
      ])
    });

    errorNumeroCelular(i) {
      return ((this.formContacto.controls['telefonos'] as FormGroup) as 
      FormGroup).controls.numeroCelular.hasError('required') ? 'Ingrese un número de celular' : '';
    }

组件.html

<mat-form-field appearance="standard">
  <mat-label>Número celular</mat-label>
  <input matInput formControlName="numeroCelular">
  <mat-error *ngIf="errorNumeroCelular()">{{errorNumeroCelular()}}</mat-error>
</mat-form-field>

标签: angulartypescriptangular-reactive-forms

解决方案


尝试这个

this.formContacto = this.fb.group({
  telefonos: this.fb.array([
    [this.createNewFormGroup()],
    [Validators.required])
  ])
});

createNewFormGroup()方法正在创建一个 FormGroup 如下

createNewFormGroup() {
    return this.fb.group({
      tipo: [''],
      numeroCelular: ['', Validators.required],
      whatsapp: [],
      codigoCiudad: [],
      numeroFijo: [],
    })
} 

访问 FormArray 的验证状态

get yourName(): FormArray {
    return this.formContacto.get('telefonos') as FormArray;
} 

HTML 模板

<label *ngIf="telefonos.errors?.required">
  your msg.
</label>
<label *ngIf="telefonos.controls[i].get('numeroCelular').errors?.required">
  your msg.
</label>

推荐阅读