How I do Angular Reactive Forms, a Little Cleaner…

Justin Miles
2 min readDec 3, 2019

When I first got into angular, I had some real complicated forms. I was working on a financial application at work that had details about various bonds and other financial instruments and forms had dynamic numbers of child forms and sometimes grandchild forms etc. Reactive forms were clearly the way to go, I loved them. But there was one thing I despised. In tutorial after tutorial, even on the angular site, I saw this:

get name() { return this.form.get('name'); } 
get email() { return this.form.get('email'); }
get password() { return this.form.get('password'); }
buildForm(){
this.form = this.fb.group({
name: [''],
email: [''],
password: ['']
})
}

They’re properties, so you can reference them without strings throughout the rest of the code, which is good, but there are still strings in the code, which just felt ugly to me. Also, I’m not a fan of keeping things on one line like that, I feel it’s just less readable, so I’d end up doing something more like :

get name() { 
return this.form.get('name');
}
get email() {
return this.form.get('email');
}
get password() {
return this.form.get('password');
}
buildForm(){
this.form = this.fb.group({
name: [''],
email: [''],
password: ['']
})
}

Here’s what I did:

form : FormBuilder;name = new FormControl('');
email = new FormControl('');
password = new FormControl('');
buildForm(){
this.form = this.fb.group({
name: this.name,
email: this.email,
password: this.password
})
}

I probably didn’t come up with it, but now I wouldn’t go back to properties without a really compelling reason. It’s only slightly more concise, but on a form with a ton of fields I think it’s a lot cleaner. I also don’t know how angular accesses things under the hood here, but if it’s as it reads, to set a value via the standard method, you would go to the FormGroup object, find the key that you’re looking for, then take that result and set the value on it. Whereas with my method, you’d just grab that FormControl and set the value. That probably isn’t the case, as angular seems to run pretty efficiently, but that’s how it reads

--

--

Justin Miles

Full-stack developer, Dad. Passionate about clean code and constantly learning. Current interests: Angular, DevOps, Domain Driven Design, and birding.