DEV Community

Cover image for Angular Form Control Aggregation
John Peters
John Peters

Posted on • Updated on

Angular Form Control Aggregation

New Discovery
Use ngModel instead!

Previous Articles have shown the value of using Form Controls in an Angular form. Validation being the most important, and secondly migrating to the Immutable model of the Angular Architecture.

What about Aggregation of Form Controls?
As the tutorials all show the Form Control is introduced as a field level validation scheme. Assume a person object definition:

 class Person{
Enter fullscreen mode Exit fullscreen mode

We would create Form Controls like this:

controls = {
  lastName: new FormControl(this.person.lastName, ...),
  middleName: new FormControl(this.person.middleName, ...),
  firstName : new FormControl(this.person.firstName,...)
Enter fullscreen mode Exit fullscreen mode

This works great but forces us to set each field value separately! The validation routines running on each change. We still want that to happen, but wouldn't it be nicer to just assign a new person object with all of the fields, responding? Let's take a look:

let fcPerson = new FormControl(this.person);
  lastName : new FormControl(fcPerson.value.lastName, ...),
  middleName : new FormControl(fcPerson.value.middleName, ...),
  firstName : new FormControl(fcPerson.value.firstName, ...)
Enter fullscreen mode Exit fullscreen mode

By doing this, we now have the ability to set the person object like this; which ripples all the changes.

Enter fullscreen mode Exit fullscreen mode

Aggregation of all the person fields into one object this.person! Also note that the GUI side doesn't need any reference to the new fcPerson form control! It lives in secret.

Watch out for improper parent control binding! Take this example:

new FormControl(fcPerson.value.lastName <- No Intellisense here
Enter fullscreen mode Exit fullscreen mode

If we don't exactly spell the fieldName properly (and intellisense doesn't work for this) the results will be a null value.


Top comments (0)