Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What makes the use of partials fail in this Angular 14 app?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:
  1. What causes this problem?
  2. What is the most reliable way to fix it?

>Solution :

You need to pass your form as an input to partial and provide the same form group name over there to make it work.

In form.component.html:

<app-additional [form]="form"></app-additional>

In additional.component.html:

<div class="more-controls" [formGroup]="form">

In additional.component.ts:

@Input() form: FormGroup;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading