Monday, 8 July 2019

Working with reactive forms - form array Angular 8

> Angular 8 Samples

Other than the below change the rest is the same as detailed under Angular 6 Reactive Forms [FormArray] section. 

In the previous versions of Angular we could access the form array like following

*ngFor="let hobbyControl of signupForm.get('hobbies').controls; let i = index"

This code will fail as of the latest Angular version.

We can fix it easily though. Outsource the "get the controls" logic into a method of the component code (the .ts file):

getControls() {
  return (this.signupForm.get('hobbies')).controls;
}


In the template, then use:

*ngFor="let hobbyControl of getControls(); let i = index"

Alternatively, we can set up a getter and use an alternative type casting syntax:

get controls() {
  return (this.signupForm.get('hobbies') as FormArray).controls;
}


and then in the template:

*ngFor="let hobbyControl of controls; let i = index"

This adjustment is required due to the way TS works and Angular parses the templates (it doesn't understand TS there).