0

I have created dynamic form inputs in angular11. need to validate the form fields which added dynamically by clicking add button. i couldnt found the right solutions. here is my code

in component.ts file

this.pollAdd = this.fb.group({
      question: ['',Validators.required],
      queChoices:this.fb.array([this.createChoice()]),
    });

addChoice(){
    this.queChoices=this.pollAdd.get('queChoices') as FormArray;
    this.queChoices.push(this.createChoice());
  }

  createChoice():FormGroup{
    return this.fb.group({
      choice:['',Validators.required],
    })
  }

get f() { return this.pollAdd.controls; }

In component.html file

<div formArrayName="queChoices" *ngFor="let choices of pollAdd.get('queChoices')['controls'];let i=index;">
        <mat-form-field class="ch__custom_input w-100 mt-3" [formGroupName]="i">
          <mat-label>Choice {{i+1}}</mat-label>
          <input matInput formControlName="choice" autofocus/>
        </mat-form-field>
      </div>

how to validate each choice field?

manikandan
  • 677
  • 2
  • 8
  • 19
  • Does this answer your question? [Angular FormArray display validation errors](https://stackoverflow.com/questions/52122433/angular-formarray-display-validation-errors) – Aman Gojariya Apr 15 '21 at 05:46

3 Answers3

1

Get the name and check if there is an error, just like a regular form.

<div *ngIf="choice.errors?.required">Choice is required</div>
Transformer
  • 6,963
  • 2
  • 26
  • 52
0
<div *ngIf="choices.controls['choice'].errors && choices.controls['choice'].touched">
            <mat-error *ngIf="choices.controls['choice'].errors?.required">Choice {{i+1}} is required!</mat-error>
          </div>

Its working for me...

manikandan
  • 677
  • 2
  • 8
  • 19
0

using mat-error, if we only has an unique error, we needn't use *ngIf, so is simply

    <mat-error>required</mat-error>

We also use a function like

  getErrorMessage(inputRef:MatFormField) {
    const control=inputRef._control?inputRef._control.ngControl:null;
    if (!control || !control.errors)
      return null;
    if (control.hasError('required')) {
      return 'You must enter a value';
    }

    return control.hasError('email') ? 'Not a valid email' : '';
  }

And pass the mat-field to the function getErrorMessage using a template reference variable

      <mat-form-field #inputRef appearance="fill">
        <mat-label>Enter your email</mat-label>
        <input  matInput placeholder="pat@example.com" [formControl]="email" required>
        <mat-error  >{{getErrorMessage(inputRef)}}</mat-error>
      </mat-form-field>
Eliseo
  • 50,109
  • 4
  • 29
  • 67