How to get the value from dynamically added nested form in angular using valueChanges?

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

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

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật