Upgrade to Pro — share decks privately, control downloads, hide ads and more …

7. Forms and simple validations

iliya
February 27, 2017
57

7. Forms and simple validations

iliya

February 27, 2017
Tweet

Transcript

  1. What do we use forms for ? • Get data

    from the user, serialize it and save it. • Validate the data and show error messages. • Populate data on initialization and display it.
  2. What do we need ? • Custom controls • Custom

    validators • Create controls dynamically
  3. Form Control • Get the value of the input •

    Input validation • User interactions • Value change https://github.com/angular/angular/blob/master/modules/%40angular/ forms/src/directives/reactive_directives/form_control_directive.ts#L26
  4. Form Array Form Control Form Control Form Control Form Control

    Form Array 0 2 3 1 Used to create dynamic forms of unknown length
  5. Forms Approaches • Template-driven approach (FormsModule | Angular 1 style)

    
 ngForm, ngModel, ngModelGroup • Model-driven approach (ReactiveFormsModule) formControlName, formGroupName, formControlArray, formControl, formGroup
  6. FormsModule vs ReactiveFormsModule • Implicit creation of FormControls by directives

    • Template as source of truth • Async • Explicit creation of FormControls • Component class as source of truth • Sync
  7. Populating data in reactive form • form.setValue(...) - you assign

    every form control value at once by passing in a data object whose properties exactly match the form model behind the FormGroup. • form.patchValue(...) - you can assign values to specific controls in a FormGroup by supplying an object of key/value pairs for just the controls of interest. (cannot check for missing control values)
  8. Resetting the form • form.reset({...}) - restores all flags to

    the pristine. The method also takes optional state value so you can reset the flags and the control values at the same.
 
 Internally, reset passes the argument to setValue
  9. NgModel • Use to track control state and validity •

    The directive doesn't just track state. It updates the control with special Angular CSS classes that reflect the state.