9

Form array value changes is not working. I can't console the value inside subscriber method. Here is my basic form array code below.

ordersData = [
 { id: 100, name: 'order 1' },
 { id: 200, name: 'order 2' },
 { id: 300, name: 'order 3' },
];

this.formGroup = this.formBuilder.group({
      testControl: this.formBuilder.array([])
  });

 get formGroupControl() {
    return (this.formGroup.get('testControl') as FormArray);
  }

 private addFormControl() {
    this.ordersData.forEach((o, i) => {
      (this.formGroup.get('testControl') as FormArray).controls.push(this.formBuilder.control(''));
    });
  }

I've called this addFormControl() function inside the ngOnInit() and if I try to see the valuechanges using this following way

this.formGroup.get('testControl').valueChanges.subscribe(value => {
      console.log('log', {value});
    });

this console is not working.. Walk me through the right way of handling form array

4
  • Where is the valueChanges snippet placed? Commented Jun 15, 2020 at 11:13
  • I don't think adding form controls will trigger a value change. It'll only happen if the values of the controls change. Commented Jun 15, 2020 at 11:20
  • valueChange is placed inside ngOninit and yes when I am trying to change the value then valueChange is not triggered. I didn't add only formControl. you can see the value is in the orderData Commented Jun 15, 2020 at 13:12
  • orderData is an array of objects and you're using it for adding as many form controls as its length. Later on, are you changing any of the values of the added form controls from the UI or programmatically? Commented Jun 15, 2020 at 13:15

1 Answer 1

33

I was having the same problem (I think), forms added to the formArray through formArray.controls.push didn't work, I fixed by using formArray.push instead

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

1 Comment

you saved my day! it makes sense now, adding to the controls array didn't actually hook the value change event together.

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.