Angular Forms -
Advanced topics

Watching for changes

Listen to AbstractControls

All AbstractControls allow you to listen
to value changes through their valueChanges attribute

this.aFormControl.valueChanges.subscribe(
   (value: string) => {
      console.log('form control value changed to:', value);
      /* Fritz Mustermann */
   });
this.form.valueChanges.subscribe(
   (formValues: any) => {
      console.log('form changed to:', formValues);
      /* {
             "address": "Formstrasse",
             "streetNumber": "10A"
         }*/
   });

Dynamically add or remove fields

Purpose

Examples:

  • Showing a checkbox only if some option had been selected by the user
  • Adding a new input field within a list, e.g. phone numbers

Why does it have to be dynamic?

FormArray and FormGroup allow to dynamically add and remove fields after the form had been created. This is important due to the following reasons:

  • You do not want to modify/overwrite the state of other FormControls while doing this operation
  • Hiding an input field will not protect it from being validated, e.g. if there is a required hidden field, the user cannot submit the form

How to add a FormControl to a FormGroup

/**
* Registers a control with the group's list of controls.
*
* This method does not update the value or validity of
* the control, so for most cases you'll want to use
* {@link FormGroup#addControl addControl} instead.
*/
registerControl(name: string, control: AbstractControl)
   : AbstractControl;
/**
* Add a control to this group.
*/
addControl(name: string, control: AbstractControl): void;

How to do remove a FormControl from a FormGroup

/**
* Remove a control from this group.
*/
removeControl(name: string): void;

How to do replace a FormControl on a FormGroup

/**
* Replace an existing control.
*/
setControl(name: string, control: AbstractControl): void;

How to add a FormControl to a FormArray

/**
* Insert a new {@link AbstractControl} at the end
* of the array.
*/
push(control: AbstractControl): void;
/**
* Insert a new {@link AbstractControl} at the given
* `index` in the array.
*/
insert(index: number, control: AbstractControl): void;
                

How to remove a FormControl from a FormArray

/**
* Remove the control at the given `index`
* in the array.
*/
removeAt(index: number): void;

How to replace a FormControl on a FormArray

/**
* Replace an existing control.
*/
setControl(index: number, control: AbstractControl): void;
                

Examples

this.subjectFormGroup.registerControl(
   'customerSubject',
   this.fb.control('', Validators.required));
this.subjectFormGroup.removeControl('customerSubject');