I'm currently working on finding a solution for patching a form array in a strongly-typed reactive Angular form. I've noticed that patchValue and setValue don't consistently work as expected with FormControl. Here's an example of the form:
this.form = fb.group<IPersonForm>({
name: new FormControl<string | null>('bob'),
phones: new FormArray<FormGroup<IPhoneForm>>([]),
});
Patching the name control is straightforward:
this.form.controls.name.patchValue('Jim', { onlySelf: true, emitEvent: false });
However, dealing with the form array poses a challenge. Let's say I create a replacement array:
const myPhone = this.fb.group<IPhoneForm>({
phone: new FormControl<string | null | undefined>('bob')
});
const array = new FormArray<FormGroup<IPhoneForm>>([myPhone]);
Now, attempting to patch (or set) the array results in compilation errors:
//this.form.controls.phones.setValue(array);
//this.form.controls.phones.setValue(array.controls);
//this.form.controls.phones.patchValue(array);
//this.form.controls.phones.patchValue(array.controls);
Although I can use setControl, this method lacks the option for onlySelf:
this.form.setControl('phones', array, { emitEvent: false });
I believe that onlySelf is essential in this scenario because when replacing the data and dealing with complex validations, I prefer to defer running them on any control until the entire form has been patched. Thank you!
For a demonstration, here's a stackblitz link: https://stackblitz.com/edit/angular-path-typed-array?file=src%2Fmain.ts