2

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

1 Answer 1

2

As a alternative solution I propose working with form array, when dealing with looping please check this example also for your reference.

import 'zone.js';
import {
  Component,
  inject,
  OnInit,
  signal,
  WritableSignal,
} from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import {
  FormBuilder,
  FormsModule,
  ReactiveFormsModule,
  FormControl,
  FormArray,
  FormGroup,
} from '@angular/forms';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [ReactiveFormsModule, FormsModule],
  template: `
    <form [formGroup] = 'employeeForm'>
     <input formControlName='orgName'>
    <div formArrayName="dynamicContent">
      @for(group of formArrayControls();track group; let i = $index){
        <div [formGroupName]="i">
          @for(controlObj of formObj;track controlObj){
            <input [formControlName]="controlObj.formControlName" 
            [type]="controlObj.type"/>
          }
        </div>
      }
    </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.array([]),
  });

  formObj = [
    {
      type: 'text',
      formControlName: 'employee',
    },

    {
      type: 'text',
      formControlName: 'empId',
    },
  ];

  ngOnInit() {
    this.employeeForm.valueChanges.subscribe((val) => console.log(val));
  }

  formArrayControls() {
    return (this.employeeForm!.get('dynamicContent') as FormArray)!
      .controls as FormGroup[];
  }

  addControl() {
    const dynamicForm = this.employeeForm.controls[
      'dynamicContent'
    ] as FormArray;
    const formGroup = this.fb.group({});
    this.formObj.forEach((elem) => {
      formGroup.addControl(elem.formControlName, new FormControl('', []));
    });
    dynamicForm.push(formGroup);
    this.showEmpInfo.update((prev) => {
      prev.push(this.formObj);
      return prev;
    });
  }
}

bootstrapApplication(App);

Stackblitz Demo


You are adding the control incorrectly, you must add the control using the method addControl. We take take a reference to the dynamic content and assign it to dynamicForm, then when we loop through the array, we use add control to add the controls directly.

addControl() {
    const dynamicForm = this.employeeForm.controls['dynamicContent'];
    this.formObj.forEach((elem) => {
      dynamicForm.addControl(elem.formControlName, new FormControl('', []));
    });
    this.showEmpInfo.set(this.formObj);
  }

Full 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.employeeForm.controls['dynamicContent'];
    this.formObj.forEach((elem) => {
      dynamicForm.addControl(elem.formControlName, new FormControl('', []));
    });
    this.showEmpInfo.set(this.formObj);
  }
}

bootstrapApplication(App);

Stackblitz Demo

Sign up to request clarification or add additional context in comments.

2 Comments

cool working like charm! Thanks
@brk updated my answer, with a small change do check it out!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.