← All posts

Mastering Nested Reactive Forms in Angular

Understanding using formGroupName directive inside child components

Reactive Forms in Angular offer powerful tools for building complex and dynamic user interfaces. While it’s common to use FormGroup within a single parent component, there are scenarios where you may want to manage form logic in child components or even nest child components within child components. In this article, we’ll explore three examples of working with nested Reactive Forms: a single-parent component, a child component, and a child-in-child component.

1. Single-Parent Component

Your form logic is contained within the same component in a single-parent component. Here’s an example of what that might look like:

// form-group-parent.component.ts 

export class FormGroupParentComponent {
public form: FormGroup<IUserForm>;

constructor() {
this.form = new FormGroup<IUserForm>({
name: new FormControl('Max'),
age: new FormControl(20),

address: new FormGroup<IAddress>({
country: new FormControl('Poland'),
city: new FormControl('Wroclaw'),

contacts: new FormGroup<IContacts>({
phone: new FormControl('123456789'),
email: new FormControl('test@test.com'),
}),

})
});
}
}

It initializes the form property with a new instance of FormGroup. The generic type <IUserForm> provides a structure that defines the expected form data.

Inside the FormGroup constructor, there are several FormControl instances nested within one another.

<!--form-group-parent.component.html-->

<form [formGroup]="form" class="form-main-container">
<div class="user-form-container border-style">
<span class="user-border-title ">
User info
</span>
<div >
<label for="name">Name:</label>
<input type="text" class="form-control" formControlName="name" id="name">
</div>
<br/>
<div formGroupName="address" class="address-form-container border-style">
<span class="user-border-title ">
Address info
</span>
<div>
<label for="country">Country:</label>
<input type="text" class="form-control" formControlName="country" id="country">
</div>
<div>
<label for="city">City:</label>
<input type="text" class="form-control" formControlName="city" id="city">
</div>
<br/>
<div formGroupName="contacts" class="border-style">
<span class="user-border-title ">
Contacts info
</span>
<div>
<label for="phone">Phone:</label>
<input type="text" class="form-control" formControlName="phone" id="phone">
</div>
<div>
<label for="email">Email:</label>
<input type="text" class="form-control" formControlName="email" id="email">
</div>

</div>
</div>
</div>
</form>

In this example, we have a three-level FormGroup structure, using formGroupName directive. But what if we want to separate some of this logic into a child component?

2. Child Component

In the case of using a child component to encapsulate part of the form, our parent component’s HTML becomes cleaner:

<!--form-group-parent.component.html-->
<form [formGroup]="form" class="form-main-container">
<div class="user-form-container border-style">
<span class="user-border-title ">
User info
</span>
<div >
<label for="name">Name:</label>
<input type="text" class="form-control" formControlName="name" id="name">
</div>
<br/>
<app-child-form-group></app-child-form-group>
</div>
</form>

And here’s our new child component:

// child-form-group.component.ts

@Component({
selector: 'app-child-form-group',
standalone: true,
imports: [CommonModule, ReactiveFormsModule, ChildInChildFormGroupComponent],
templateUrl: './child-form-group.component.html',
styleUrls: ['./child-form-group.component.scss'],
viewProviders: [{ provide: ControlContainer, useExisting: FormGroupDirective }]
})
export class ChildFormGroupComponent {}

The main point here is to add the viewProviders configuration to our Angular @Component decorator.

This configuration is used to provide the component with access to the FormGroupDirective, which is required for working with Reactive Forms. The provide property indicates the token or service that should be provided, and useExisting specifies that it should use an existing instance of FormGroupDirective.

Inside the child HTML component, we just need to copy and past logic from the parent component:

<!-- child-form-group.component.html -->

<div formGroupName="address" class="address-form-container border-style">
<span class="user-border-title ">
Address info
</span>
<div>
<label for="country">Country:</label>
<input type="text" class="form-control" formControlName="country" id="country">
</div>
<div>
<label for="city">City:</label>
<input type="text" class="form-control" formControlName="city" id="city">
</div>
<br/>
<div formGroupName="contacts" class="border-style">
<span class="user-border-title ">
Contacts info
</span>
<div>
<label for="phone">Phone:</label>
<input type="text" class="form-control" formControlName="phone" id="phone">
</div>
<div>
<label for="email">Email:</label>
<input type="text" class="form-control" formControlName="email" id="email">
</div>

</div>
</div>

3. Child-in-Child Component

Now, let’s take it a step further and nest another child component within our child component:

// child-in-child-form-group.component.ts

@Component({
selector: 'app-child-in-child-form-group',
standalone: true,
imports: [CommonModule, ReactiveFormsModule],
templateUrl: './child-in-child-form-group.component.html',
styleUrls: ['./child-in-child-form-group.component.scss'],
viewProviders: [{ provide: ControlContainer, useExisting: FormGroupDirective }]
})

export class ChildInChildFormGroupComponent implements OnInit{
private formGroupDirective = inject(FormGroupDirective);
public parentForm!: FormGroup;
public contactsForm!: FormGroup;

ngOnInit(): void {
this.parentForm = this.formGroupDirective.form;
this.contactsForm = this.parentForm.get('address')?.get('contacts') as FormGroup;
}
}

This piece of code assigns the form property of FormGroupDirective to the parentForm property. This means that the component is accessing and storing a reference to the parent form, likely for interaction or data retrieval. We also obtain a nested FormGroup named “contacts” within the “address” group using the get method.

Next, we have to use the “contactsForm” in formGroup directive in our HTML component, without formGroupNamedirective:

<!-- child-in-child-form-group.component.html -->

<div [formGroup]="contactsForm" class="border-style">
<span class="user-border-title ">
Contacts info
</span>

<div>
<label for="phone">Phone:</label>
<input type="text" class="form-control" formControlName="phone" id="phone">
</div>
<div>
<label for="email">Email:</label>
<input type="text" class="form-control" formControlName="email" id="email">
</div>

</div>

In this example, we have successfully used a child component within another child component, providing a clear and organized structure for managing complex forms.

Using some CSS you can achieve this result in UI:

The result in UI

In summary, these techniques for nesting Reactive Forms in Angular components offer flexibility and maintainability in your projects, making your code more modular and easier to manage.

Source code: https://github.com/TeslenkoOleg/Angular_Nested_Reactive_Forms

Documentation links:

  1. https://angular.io/guide/reactive-forms
  2. https://angular.io/guide/typed-forms

And there we have it. I hope you have found this useful. Thank you for reading. If you have any questions you can find me on LinkedIn. You can also see my previous articles:

In Plain English

Thank you for being a part of our community! Before you go: