What is the Angular 2 RC5 way to write template-based forms?

I have to say that I am completely confused by various online tutorials on the RC5 Angular forms. The official documentation also does not eliminate the confusion.

An abundance of directives (ngForm, ngModel, ngFormControl, ngControl, ngFormControlName, ngControlName, did I miss something?) Some of them are outdated, and some are not.

In addition, all study guides go a simple way - simple text inputs or controls. And if I need switches and checkboxes?

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

Is there an example somewhere updated and explaining:

  • Using the four main controls - text input / radio / checkbox and selection?
  • Additional goodies such as dirty / untouched, validation?
  • Form Model (FormBuilder, FormGroup, FormControl, etc.)

PS

What did i read?

I'm probably stupid, but I still don't know how to write forms in RC5 correctly.

+5
source share
2 answers

What I found really confusing in angular2 forms is that there are two completely different ways to create them, and the two methods do not mix well. You have a “managed template” where the form is built and processed as much as possible in html, and then you have a “managed model” where the form is processed from the component side.

The best description of the various types that I have found is a video where Kara Erickson demonstrates both. She very well explains the differences between the marks of 10-11 minutes:

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

In short:


Template Driven Forms

If you want to perform all form processing (binding, validation, etc.) in an html template, use the following directives:

  • ngModel
  • ngModelGroup
  • ngForm

Molded Models (also known as Reactive Forms )

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

  • Formgroup
  • Formcontrol
  • FormArray
  • optionally use FormBuilder to reduce some templates

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

  • formControlName
  • formGroupName

Edit 2016-09-02: There is a good cookbook in the white papers with good coverage of the differences between the templates / reactive forms: https://angular.io/docs/ts/latest/cookbook/form-validation.html

+1
source

I like FormBuilder because most of the code is in ts, not html, so it’s better to check the compilation time. This page from the Angular2 documentation has a simple example .

PrimeNG has some great controls that use FormBuilder
In addition, I have code here that may be useful to illustrate valid / invalid

-1
source

All Articles