0

I made a dynamic field form in which the user can add more fields. I want to detect the changes in libId But the changes are only detecting for the first field.

My code-

 this.invoiceForm = this._fb.group({
        itemRows: this._fb.array([this.initItemRows()]) // here
      });


    (<FormArray>this.invoiceForm.get('itemRows')).controls.forEach(
      control => {
        console.log('reaches');
        control.get('libId').valueChanges
          .pipe(
            distinctUntilChanged()
          )
          .subscribe(value => console.log(value));
      }
    );

      initItemRows() {
        return this._fb.group({
          // list all your form controls here, which belongs to your form array

          libId: [null, Validators.required],
          rollNumber: [null, Validators.required]
        });
      }


  addNewRow() {
    // control refers to your formarray
    const control = <FormArray>this.invoiceForm.controls['itemRows'];
    // add new formgroup
    control.push(this.initItemRows());
  }

I am using this code inside the ngOnInit. I don't know why changes are not being detected for any other field.

Please suggest some solutions.

2
  • Why not handle it using the (change) event on the input? Commented Sep 17, 2018 at 16:17
  • @SiddAjmera, I tried But (change) is not working of the key press, It is only working when I click outside after value change. Commented Sep 17, 2018 at 16:27

1 Answer 1

1

There is example:

    const formGroup = this.fb.group({
        libId: [null, Validators.required],
        rollNumber: [null, Validators.required]
    });

    formGroup.controls.libId.valueChanges.subscribe(val => console.log(val));
    formGroup.controls.rollNumber.valueChanges.subscribe(val => console.log(val));

    this.form = this.fb.group({
        itemRows: new FormArray([formGroup])
    });

    // I've just added another form group but this should be in method - addNewRow
    const formGroup1 = this.fb.group({
        libId: [null, Validators.required],
        rollNumber: [null, Validators.required]
    });

    formGroup1.controls.libId.valueChanges.subscribe(val => console.log(val));
    formGroup1.controls.rollNumber.valueChanges.subscribe(val => console.log(val));

    (this.form.controls.itemRows as FormArray).controls.push(formGroup1);
    //

    ((this.form.controls.itemRows as FormArray).controls[0] as FormGroup).controls.libId.setValue('abc');
    ((this.form.controls.itemRows as FormArray).controls[1] as FormGroup).controls.rollNumber.setValue('xyz');

Feel free to ask if you have questions.

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

Comments

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.