Member-only story

The Best Way to build reactive sub-forms with Angular

Tomas Trajan
11 min readJan 21, 2020

--

Original 📸 by Zdeněk Macháček

In this article we’re going to explore various approaches how to implement reactive sub-forms and discuss their trade-offs. At the end you will be able to make informed decision based on the particular use case to deliver best possible experience for your users and great developer experience for your colleagues!

Forms represent one of the most important parts of almost all frontend applications. From a single input field to a multi step wizards, forms enable dialog with the users by providing them with a way to submit many different kinds of data!

When developing Angular application, we will rarely end up with just a single form. It is much more common to implement many different forms for the individual features based on user requirements.

It is quite usual that some of the forms (or their parts) will feel repetitive as we keep re-implementing them over and over again!

An Example

Let’s say we’re implementing a customer form. There will most likely be a part of that customer form which will hold address data. We will use Angular reactive forms and a nested FormGroup to describe address object with properties (and inputs) for stuff like street, city or zip code.

The implementation using provided FormBuilder will look something like this…

Notice how we define nested form group using the FormBuilder .group() method to define address sub-form

The address sub-form is implemented inline using formGroupName directive on the <div> which allows us to access nested form controls like fromControlName="street" which are children of that element directly instead of writing "street.address".

We could achieve nice look and feel by using great Angular Material component library which provides nicely styled inputs (together with other form controls like selects, slides, …)

Cool, we have our customer form and it…

--

--

Tomas Trajan
Tomas Trajan

Written by Tomas Trajan

👋 I build, teach, write & speak about #Angular & #NgRx for enterprises 👨‍💻 Google Developer Expert #GDE 👨‍🏫 @AngularZurich meetup co-organizer

Responses (18)

Write a response