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?

1

3 Answers 3

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>
Sign up to request clarification or add additional context in comments.

3 Comments

its showing console error ERROR TypeError: Cannot read property 'errors' of undefined
You can't just blindly copy and paste code from the answer.
yes i have tried but its showing errors undefined error
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...

1 Comment

using mat-error, if you has only an unique error, you needn't use *ngIf
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="[email protected]" [formControl]="email" required>
        <mat-error  >{{getErrorMessage(inputRef)}}</mat-error>
      </mat-form-field>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.