在Angular 4中检测formGroup和formArray中的valueChange时出现问题

问题描述 投票:0回答:1

我创建了一个动态字段表单,用户可以在其中添加更多字段。我想检测libId中的变化但是这些变化只是检测到第一个字段。

我的代码 -

 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());
  }

我在ngOnInit中使用此代码。我不知道为什么没有检测到任何其他字段的更改。

请提出一些解决方案。

angular typescript
1个回答
1
投票

有例子:

    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');

如果您有任何疑问,请随时询问。

© www.soinside.com 2019 - 2024. All rights reserved.