Z
Z
zlodiak2019-10-12 23:24:11
JavaScript
zlodiak, 2019-10-12 23:24:11

Why is the nested form not validating?

I'm trying to create a nested form based on formGroups . Here is my form model:

this.formGroup = this.formBuilder.group({
      'vehType': [null, Validators.required],
      'gosNum': [null, Validators.required],
      'body': this.formGroup = this.formBuilder.group({
        'bodyCapacity': [null, [Validators.required]],
        'bodyVolume': [null, [Validators.required]],
      }),
      'trailer': this.formGroup = this.formBuilder.group({
        'trailerCapacity': [null, [Validators.required]],
        'trailerVolume': [null, [Validators.required]],
      }),
    });

Here is the relevant template:
<form [formGroup]="formGroup" (ngSubmit)="onSubmit(formGroup.value)" class="form">

    <mat-card>
      <mat-form-field>
        <mat-select  formControlName="vehType">
          <mat-option *ngFor="let option of vehTypes" [value]="option">
            {{ option }}
          </mat-option>
        </mat-select>
      </mat-form-field>
      <mat-form-field>
        <input matInput placeholder="gosNum" formControlName="gosNum">
      </mat-form-field>      
    </mat-card>

    <mat-card [formGroupName]="body">
      <mat-form-field>
        <input matInput placeholder="bodyCapacity" formControlName="bodyCapacity">
      </mat-form-field>  
      <mat-form-field>
        <input matInput placeholder="bodyVolume" formControlName="bodyVolume">
      </mat-form-field>        
    </mat-card>

    <mat-card [formGroupName]="trailer">
      <mat-form-field>
        <input matInput placeholder="trailerCapacity" formControlName="trailerCapacity">
      </mat-form-field>  
      <mat-form-field>
        <input matInput placeholder="trailerVolume" formControlName="trailerVolume">
      </mat-form-field>        
    </mat-card>    

    <div>
      <button mat-raised-button type="submit" [disabled]="!formGroup.valid">Submit Form</button>
    </div>

  </form>

The problem is that even with all the fields filled in, the nested parts of the form are invalid and the entire form is invalid. This can be seen through the debug button that I have placed at the bottom of the page in the LIVE DEMO
Please help fix the validation so that:
1. when all fields are filled in, the parent form is valid.
2. If the fields of the nested form are filled in, the nested form is valid, and the parent form is not required.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2019-10-12
@zlodiak

<mat-card [formGroupName]="body">
component has no body field
type error

Cannot find control with unspecified name attribute
in the console did not confuse chtol?
Remove the square brackets and everything will work. Like this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question