Cannot read Property 'hasError' of Undefined when trying to put Validator required

Asked

Viewed 363 times

0

I’m trying to put a required Validator in a field, but I’m getting:

ERROR Typeerror: Cannot read Property 'hasError' of Undefined

I tried something like:

<form [formGroup]="variacaoForm">

My function that creates this form group:

this.variacaoForm = this.fb.group({

  variacoes: this.fb.array([this.createFormGroup()])

});

createFormGroup(produto?: any, indice?: number): FormGroup {
    return this.fb.group({
      sku: new FormControl('', [Validators.required
      ]),
    });
  }

Here I try to show with hasError a mandatory field message:

  <div class="col-12 col-md-12 col-lg-6 colunasVariacao margemcoluna">
    <label class="colorLabel" for="sku{{i}}">SKU *</label>
    <input name="sku{{i}}" required formControlName="sku" type="text" class="form-control">

    <p *ngIf="sku.hasError('required')" class="primary-color">Campo obrigatório</p>

  </div>
  • Have you tried sku?.hasError('required')"

1 answer

1

this error occurs because the sku object is not of the Formcontrol type. You can try to access the sku object: variacaForm.controls.variacoes.Controls[i].controls.sku.hasError('required')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.