Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...)

P.S.

What I read?

  • https://angular.io/docs/ts/latest/guide/forms.html
  • https://scotch.io/tutorials/using-angular-2s-template-driven-forms
  • https://scotch.io/tutorials/using-angular-2s-model-driven-forms-with-formgroup-and-formcontrol
  • https://angular.io/docs/ts/latest/cookbook/dynamic-form.html
  • http://blog.rangle.io/how-angular-2-form-models-work/
  • http://blog.rangle.io/data-angular-2-forms/

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

like image 813
mark Avatar asked Nov 19 '22 20:11

mark


1 Answers

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:

https://www.youtube.com/watch?v=E92KS_YCSf8

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: https://angular.io/docs/ts/latest/cookbook/form-validation.html

like image 176
nickspoon Avatar answered Nov 22 '22 08:11

nickspoon