Angular Forms

There are two types of forms:
1) Reactive forms: scalable, reusable and testtable
2)Template driven forms: simple

Data flow in Reactive forms:
-As user types value in input, input event is emitted with latest value by input element.
-The control value accessor(links FormControl instances and native DOM elements) sends new value to FormControl instance. like: favouriteColorControl.setValue('red'), Here favouriteColorControl is control value accessor.
-FormControl instance emits new values through valueChanges observable.
-Any subscriber to valueChanges observable receives the new value.

Data flow in Template driven forms:
-All the steps are same as above
-The control value accessor also calls the NgModel.viewToModelUpdate() method which emits an ngModelChange event.
-The favoriteColor property in the component is updated to the value emitted by the ngModelChange event

Differences:
-Reactive forms are created in component class while template driven forms are created by directive.

Mutability:
-In reactive forms, the FormControl instance always return new value when control's value is updated.
-In template driven forms, control value accessor is always modified.

Form validation:
-In reactive forms, we define custom validators as functions for validation.
-Template driven forms, are tied to directive so we need to define custom directive that holds functions for validation.

Data flow in Reactive forms:
-As user types value in input, input event is emitted with latest value by input element.
-The control value accessor(links FormControl instances and native DOM elements) sends new value to FormControl instance. like: favouriteColorControl.setValue('red'), Here favouriteColorControl is control value accessor.
-FormControl instance emits new values through valueChanges observable.
-Any subscriber to valueChanges observable receives the new value.
-The Control value accessor set the new value in the element.

Data flow in Template driven forms:
-All the steps are same as above
-The control value accessor also calls the NgModel.viewToModelUpdate() method which emits an ngModelChange event.
-The favoriteColor property in the component is updated to the value emitted by the ngModelChange event

FormGroup defines set of form controls
FormArray defines a dynamic form, where you can add/remove fields on dynamically on run time.

ways to access form:
this.searchForm.get('endDate').setValue()
this.searchForm.controls['endDate'].setErrors({ 'incorrect': true });

setValue() method set a new value to individual control. e.g. this.name.setValue('Nancy') or this.searchForm.get('endDate').setValue()
patchValue() method updates multiple controls at at a time as we pass an object containing properties which needs to be changed. e.g.
this.searchForm.patchValue({
    firstName: 'Nancy',
    address: {
      street: '123 Drew Street'
    }
  });

FormBuilder is easy way to create multiple forms as it has shorter syntext. It has three methods control(), group(), array().
Using FormBuilder:
import { FormBuilder } from '@angular/forms';
constructor(private fb: FormBuilder) { }
profileForm = this.fb.group({
  firstName: [''],
  lastName: [''],
  address: this.fb.group({
    street: [''],
    city: [''],
    state: [''],
    zip: ['']
  }),
});

Using FormGroup:
profileForm = new FormGroup({
  firstName: new FormControl(''),
  lastName: new FormControl(''),
  address: new FormGroup({
    street: new FormControl(''),
    city: new FormControl(''),
    state: new FormControl(''),
    zip: new FormControl('')
  })
});

Validation:
import { FormBuilder } from '@angular/forms';
import { Validators } from '@angular/forms';
constructor(private fb: FormBuilder) { }
profileForm = this.fb.group({
  firstName: ['', Validators.required],  //define validators like this
  lastName: [{ value: 'RSS', disabled: true }, [Validators.required, Validators.maxLength(5)]], //set default values and disabled
});

Dynamically add/remove controls in form using FormArray
[Refer]-https://www.tektutorialshub.com/angular/angular-formarray-example-in-reactive-forms/


Form Input validation:
There are two types of validator functions:
1)Sync validators: immediately take control and return validation errors or null. we can pass these as second argument while defining form group.  e.g. firstName: ['', Validators.required],
2)Async validators: takes control and returns Promise or Observable function and later emit validation errors. We can pass them as third argument while defining form group.

Comments