Home > Software engineering >  What makes the use of partials fail in this Angular 14 app?
What makes the use of partials fail in this Angular 14 app?

Time:02-03

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 >Fast name:</mat-label>
    <input  matInput formControlName="first_name" />
  </mat-form-field>

  <mat-form-field appearance="outline" floatLabel="always">
    <mat-label >Last name:</mat-label>
    <input  matInput formControlName="last_name" />
  </mat-form-field>

  <app-additional></app-additional>

  <div >
    <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?

CodePudding user response:

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  [formGroup]="form">

In additional.component.ts:

@Input() form: FormGroup;

CodePudding user response:

The problem is caused because the form control inside the partial component () is not bound to a parent FormGroup directive.

To fix this problem, you can pass the form FormGroup from the parent component to the partial component using property binding ([form]="form") and bind the form control inside the partial component to the parent FormGroup using formControlName and formGroup directive.

just like this :

<form [formGroup]="form">
  <!-- ... -->
  <app-additional [form]="form"></app-additional>
  <!-- ... -->
</form>
  • Related