Member-only story

How to make reusable forms in Angular

It’s easier then you might think.

Daniel Kreider
3 min readSep 24, 2024
Photo by Zarak Khan on Unsplash

It’s time for a dive into reusable Angular forms.

Today you’ll learn how to reuse your form control or the group of form controls by extracting them into a separate component.

And then reuse this component in other Angular forms in your angular application.

So pull out your favorite code editor and let’s learn how to make reactive form controls reusable in your applications.

1. Create the reusable form group

We’ll begin by generating a component that will hold our reusable form group.

ng generate component name-group

And then use this for the component’s code.

import { Component, Input, inject } from '@angular/core';
import { ControlContainer, FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';

@Component({
selector: 'app-name-group',
standalone: true,
imports: [ReactiveFormsModule],
viewProviders: [
{
provide: ControlContainer,
useFactory: () => inject(ControlContainer, {skipSelf: true})
}
],
template: `
<fieldset [formGroupName]="controlKey">
<legend>{{label}}</legend>
<div class="form-field">
<label…

--

--

Responses (3)