繁体   English   中英

如何订阅表单数组上特定字段的更改

[英]how can I subscribe to changes on a specific field on a form Array

我的应用程序包含一个表单数组,该数组具有基于其他字段的不同自动计算字段,因此我需要订阅某些字段的值更改,但这是我第一次使用表单数组。
这是我用来制作数组形式的代码

constructor(public FormBuilder: FormBuilder  ) {
    this.testForm=  new FormGroup({
      formArrayName: this.FormBuilder.array([])
    });
    this.buildForm();
  }

buildForm() {
    const controlArray = this.testForm.get('formArrayName') as FormArray;

    Object.keys(this.options).forEach((i) => {
      controlArray.push(
        this.FormBuilder.group({
            id_agent : [this.options[i].ID , Validators.required] ,
            calls :  [0] ,
            CA : { value: 0, disabled: true } ,
            RPC : { value: 0, disabled: true } ,
            CR : { value: 0, disabled: true } ,
            ACU : { value: 0, disabled: true } ,
            CB : [0] ,
            RP : [0] ,
            NGT : { value: 0, disabled: true } ,
            sells : { value: 0, disabled: true } ,
            week : ['' , Validators.required] ,
          }
        )
      );
    });  
  }

我设法像这样订阅整个控件的值更改

controlArray.controls.forEach((control ,index)=> {
      control.valueChanges.subscribe(value => {
       console.log(value)
    });
    });

这行得通,但是我需要订阅特定的字段,我尝试使用它,但是它进入了无限循环,我可以理解为什么它是错误的。
所以我需要类似的东西:

controlArray.controls.forEach((control ,index)=> {
          control['calls'].valueChanges.subscribe(value => {
           console.log(value)
        });
        });

我顺便试了一下,我得到了Cannot read properties of undefined (reading 'valueChanges')错误

这是一个关于订阅 FormArray 的某些字段以及基于某些条件值的现场演示。 Angular 订阅 Formarray 值更改 - StackBlitz

但是,在我的情况下,想要订阅整个 FormArray 并过滤某些字段 valueChange 以停止进一步订阅 FormArray。

 constructor(private fb:FormBuilder) { this.itemsForm = this.fb.group({ market: ['', Validators.required], items: this.fb.array([]), }); } ngOnInit(): void{ // push some items in FormArray this.addItem(); this.addItem(); this.itemsForm.get("items")?.valueChanges.pipe( pairwise(), filter(([oldItemsArray, newItemsArray]) => { for(var i=0; i<oldItemsArray.length && oldItemsArray.length == newItemsArray.length; i++){ if (newItemsArray[i].rate.= oldItemsArray[i].rate || newItemsArray[i].name,= oldItemsArray[i].name ) // means name has been change: so don't subscribe { console;log("Stop to further subscriber; "+i), return false; //if both conditions are true. then stop for further subscribe } } return true. }) );subscribe(()=> this:onNormalFormChange() ). } get itemArray(). FormArray { return this:itemsForm.get("items") as FormArray } newItem(). FormGroup { return this:fb,group({ name: '', weight: '', rate: '', cost. ''. }) } addItem() { this.itemArray;push(this:newItem()). } removeItem(i.number) { this;itemArray.removeAt(i); } onNormalFormChange(){ console.log("Subscriber Successful") }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM