0

I'm trying to validate my forms using an array of FormGroups.

It was working before adding an array of FormGroups (material stepper validation purposes).

HTML:

<form [formGroup]="formGroup" (ngSubmit)="submit()">
<mat-form-field>
    <input matInput formControlName="fullName" required>
    <mat-error *ngIf="formGroup.controls.formArray.controls['fullName'].errors?.required">Required</mat-error>
</mat-form-field>

<mat-form-field>
    <input matInput formControlName="shortName" required>
    <mat-error *ngIf="formGroup.controls.formArray.controls['shortName'].errors?.required">Required</mat-error>
</mat-form-field>
</form>

TS:

get formArray(): AbstractControl | null { return this.formGroup.get('formArray'); }

this.formGroup = this.fb.group({
    formArray: this.fb.array([
        this.fb.group({ fullName: [null, [Validators.required]] }),
        this.fb.group({ shortName: [null, [Validators.required]] }),
    ])
});

What am I doing wrong?

2
  • That just looks strange... usually when we have a form array, it contains formgroups with the same form controls. Why would you need formarray and nested formgroups? Why not just form controls? Commented Jul 26, 2019 at 17:13
  • This way I'm able to work with linear angular's material steppers without creating extra FormGroups Commented Jul 26, 2019 at 17:48

1 Answer 1

2

your array here is an array of groups and you need to treat it as such, btw, this is a weird way to do this...

<form [formGroup]="formGroup" (ngSubmit)="submit()">
  <ng-container formArrayName="formArray">
    <mat-form-field formGroupName="1">
        <input matInput formControlName="fullName" required>
        <mat-error *ngIf="formGroup.controls.formArray.controls[1].controls['fullName'].errors?.required">Required</mat-error>
    </mat-form-field>

    <mat-form-field formGroupName="2">
        <input matInput formControlName="shortName" required>
        <mat-error *ngIf="formGroup.controls.formArray.controls[2].controls['shortName'].errors?.required">Required</mat-error>
    </mat-form-field>
  </ng-container>
</form>

so what I've added is a container referencing the form array name and then directives letting it know the formGroupName (which is the index in the case of a FormArray) for each control in the array. I've also added a step in your validation check where I access the formarray control index. I'm not sure at all why you need or would want this structure, but this will work now.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.