Dynamically changing reactive forms Controls form FormControl to FormArray.
Reactive form group:
profileForm = this.fb.group({
name: [''],
mobile: ['']
});
OR
profileForm = this.fb.group({
name: [''],
mobile: this.fb.array([
this.fb.control('')
])
});
Rendering profileForm using formConfig Map:
formConfigMap = new Map([
[
'client',
[{key: 'name', multi: false}, {key: 'mobile', multi: false}],
],
[
'customer',
[{key: 'name', multi: false}, {key: 'mobile', multi: true}],
],
]);
HTML:
<form [formGroup]="profileForm">
<div *ngFor="let field of formConfigMap.get('client' OR 'customer')">
<div *ngIf="field.multi; else singleControl" formArrayName="mobile">
<div *ngFor="let control of mobile.controls; let i=index">
<input type="text" [formControlName]="i">
</div>
</div>
<ng-template #singleControl>
<input type="text" [formControlName]="field.key">
</ng-template>
</div>
</form>
Whenever I am changing profileForm object form 'client' to 'customer', I am getting "TypeError: control.registerOnChange is not a function" Error. because of dynamically changing in reactive forms Control(mobile: FormControl -> FormArray).
If I am changing profileForm object from 'customer' to 'client', It works perfectly fine (mobile: FormArray -> FormControl).
Any suggestion will help.
I have tried "removeControl(name: string)" method to remove control(mobile: FormControl) first and then "addControl(name, control)" method to add control(mobile as FormArray).