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
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 rootlevel 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 propertiesof the groups (name, email, country and city) are FormControls .
And that’s it!
We are ready to use our form in thisHTML 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.
Next week, Observables !