【问题标题】:Validation control inside formGroup inside formArrayformArray里面的formGroup里面的验证控件
【发布时间】:2021-03-29 15:00:44
【问题描述】:

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

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

我有以下几点:

component.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' : '';
    }

components.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>

【问题讨论】:

    标签: angular typescript angular-reactive-forms


    【解决方案1】:

    试试这个

    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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-10
      • 2017-11-09
      • 2019-05-28
      • 1970-01-01
      • 2011-03-11
      • 2020-11-10
      • 2018-11-10
      • 2021-04-27
      相关资源
      最近更新 更多