mark mark - 1 year ago 207
Javascript Question

What is the Angular 2 RC5 way of writing template based forms?

I must say I am totally confused by the different tutorials on the web about RC5 Angular forms. The official documentation does not clear up the confusion either.

The abundance of directives (ngForm, ngModel, ngFormControl, ngControl, ngFormControlName, ngControlName, did I miss anything?) some are deprecated, some are not.

Plus, all the tutorials go the easy path - plain text inputs or select controls. And if I need radio buttons and checkboxes?

In short, I have no idea how to write forms in RC5.

Is there an example somewhere, that is up-to-date and explains:

  1. The usage of the 4 basic controls - input text/radio/checkbox and select?

  2. The extra goodies, like dirty/pristine, validation?

  3. The form model (FormBuilder, FormGroup, FormControl, etc...)


What I read?

I am probably stupid, but I still do not know what is the right way to write forms in RC5.

Answer Source

The thing that I found really confusing about angular2 forms is that there are two quite different ways of building them, and the two ways don't mix very well. You have "template driven", where the form is built and handled as much as possible in the html, and then you have "model driven" where the form is handled on the component side.

The best description of the different types I've found is this video, where Kara Erickson does a demo of both. She explains the differences very well around the 10-11 minute mark:

In short:

Template driven forms

If you want to do all your form handling (binding, validation etc.) in the template html, use these directives:

  • ngModel
  • ngModelGroup
  • ngForm

Model-driven forms (also known as Reactive forms)

If you want to have finer control, better testability, custom validators etc., generate the form manually in the component using these controls:

  • FormGroup
  • FormControl
  • FormArray
  • optionally use a FormBuilder to reduce some boilerplate

Then bind your html form and input elements to these controls using these directives:

  • formControlName
  • formGroupName

Edit 2016-09-02: There is now a good cookbook in the official docs with good coverage of the differences between template/reactive forms:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download