I am working on a with nested form groups in Angular 14.
There are form controls common to multiple forms so I have added them in a partial.
In form.component.ts
I have:
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, FormArray } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css'],
})
export class FormComponent {
public form: FormGroup = new FormGroup({
first_name: new FormControl('', Validators.required),
last_name: new FormControl('', Validators.required),
email: new FormControl('', [Validators.required, Validators.email]),
phone: new FormControl('', Validators.required),
});
constructor() {}
ngOnInit(): void {}
public sendFormData() {
console.log(this.form.value);
}
}
In form.component.html
I include the partial <app-additional></app-additional>
:
<form [formGroup]="form">
<mat-form-field appearance="outline" floatLabel="always">
<mat-label class="mat-label">Fast name:</mat-label>
<input class="mat-input" matInput formControlName="first_name" />
</mat-form-field>
<mat-form-field appearance="outline" floatLabel="always">
<mat-label class="mat-label">Last name:</mat-label>
<input class="mat-input" matInput formControlName="last_name" />
</mat-form-field>
<app-additional></app-additional>
<div class="center">
<button
(click)="sendFormData()"
mat-raised-button
color="primary"
[disabled]="!form.valid"
>
Submit
</button>
</div>
</form>
See Stackblitz HERE.
The problem
Instead of rendering the partial, the app throws the error:
Error: formControlName must be used with a parent formGroup directive.
Questions:
- What causes this problem?
- What is the most reliable way to fix it?