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



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

的代码
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 Valuechanges - 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")
}

最新更新