Angular 2 Reactive Forms in One Go

Another sweet and short tuts today!
Following the article on the Template-Driven Forms here, we switch to Reactive Forms also called Model-Driven Forms.
We will skip the User Model this time and just focus on the form itself.

As usual we start by adding the corresponding module to our app.module file:

Switching to our HomeComponent controller:

All we need here is FormBuilder (I also imported FromGroup but it’s only for clear typing).
Once again we will stock our form values in the userForm variable.
formBuilder will create the root level group and pass it to userForm.
Finally we build the address sub-group by asking formBuilder to give us another group.
Keep in mind that each properties of the groups (name, email, country and city) are FormControls.

And that’s it!

We are ready to use our form in this HTML template:

So compared to the Template-Driven method what changed here?
Only 3 new words: formGroup, formControlName and formGroupName.

  • formGroup links our previously created userForm
  • formControlName links our formControls (name, email …)
  • formGroupName links our address formGroup

On submit we will have our form available in our onFormSubmitted function.
I’d like to dive deeper however we will need more knowledge about Observables.
So let’s keep it light for now.

Subscribe to my mailing list to get access to a Free 7-day Ionic 3 introduction email course!
100% Privacy. I'll never spam you!
Next week, Observables!
Stay tuned.

 

No Comments Yet

Leave a Reply

2 Shares