loading...
Cover image for Don't Use Form Control Aggregation

Don't Use Form Control Aggregation

jwp profile image John Peters Updated on ・2 min read

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{
  lastName:string;
  middleName:string;
  firstName:string;
}

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,...)
}

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);
controls={
  lastName : new FormControl(fcPerson.value.lastName, ...),
  middleName : new FormControl(fcPerson.value.middleName, ...),
  firstName : new FormControl(fcPerson.value.firstName, ...)
}

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

fcPerson.setValue(this.person);

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.

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

new FormControl(fcPerson.value.lastName <- No Intellisense here

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

JWP2020

Discussion

pic
Editor guide