Access Angular reactive form controls using getters

mohit thakur
1 min readApr 30, 2020

I believe most of the angular developers out there have ended up working on reactive forms. I know these forms can get even complex when in an enterprise application

This is little hack that will save hours of debugging time for you and also for others on your team. And bring in one of the basic principles of programming DRY(do not repeat yourself)

How we usually access a form control in our angular component

profileForm =
this.fb.group({
firstName: ['', Validators.required],
lastName: [''],
address: this.fb.group({
street: [''],
city: [''],
state: [''],
zip: ['']
}),
});
//access the firstname value
this.profileForm.get('firstName').value

Now lets see how we change value of the control

this.profileForm.get('firstName').patchValue('oops');
this.profileForm.get('firstName').reset();
// many methods can be accessed in this way, but the
this.profileForm.get is repeated all the time

The Better Way

  • create a getter for the form and the control
// old way to access the firstname value
this.profileForm.get('firstName').value
/*----- create getters -----*/
get form(){
return this.profileForm;
}
get firstName(){
return this.form.get('firstName');
}

Now Access control easily by just calling the getter

this.firstName.patchValue('I am so happy now');
this.firstName.reset();
this.firstName.disable();

Easy hack but makes code cleaner and easy to maintain.

Try this out and happy coding

--

--