I am dynamically adding formControl to a parent form by iterating an array of objects & want to track the change in these dynamically added controls by adding the valueChanges to the parent form inside the ngOnInit method
In my code, the valueChanges is only able to track the changes of the inputs already present in the form but cannot track the change of the elements added dynamically.
Here is my code
import 'zone.js';
import {
Component,
inject,
OnInit,
signal,
WritableSignal,
} from '@angular/core';
import {
bootstrapApplication
} from '@angular/platform-browser';
import {
FormBuilder,
FormsModule,
ReactiveFormsModule,
FormControl,
} from '@angular/forms';
@Component({
selector: 'app-root',
standalone: true,
imports: [ReactiveFormsModule, FormsModule],
template: `
<form [formGroup] = 'employeeForm'>
<input formControlName='orgName'>
@if(showEmpInfo().length > 0){
<div formGroupName="dynamicContent">
@for(emp of showEmpInfo();track emp){
<input type = 'text'
[formControlName] = "emp.formControlName">
}
</div>
}
<button (click) ='addControl()'>Add</button>
</form>
`,
})
export class App implements OnInit {
fb = inject(FormBuilder);
showEmpInfo: WritableSignal < any[] > = signal([]);
employeeForm = this.fb.group({
orgName: [''],
dynamicContent: this.fb.group({}),
});
formObj = [{
type: 'text',
formControlName: 'employee',
},
{
type: 'text',
formControlName: 'empId',
},
];
ngOnInit() {
this.employeeForm.valueChanges.subscribe((val) => console.log(val));
}
addControl() {
const dynamicForm = this.fb.group({});
this.formObj.forEach((elem) => {
dynamicForm.addControl(elem.formControlName, new FormControl('', []));
});
this.employeeForm.controls['dynamicContent'] = dynamicForm;
this.showEmpInfo.set(this.formObj);
}
}
bootstrapApplication(App);
But if I add valueChanges to dynamicForm control like this.dynamicForm.valueChanges after dynamically adding the content, it can track the change of the dynamic contents.
My question is, how can I avoid adding this.dynamicForm.valueChanges after iteration and track changes in the dynamic control by only adding valueChanges to the root formGroup which is done inside the ngOnit?
You can see console.log does not log when typing in the dynamically added control but logs only when typing in the static formControls
Here is the Stackblitz Demo Link