gpt4 book ai didi

Angular - FormArray 的 valueChanges

转载 作者:行者123 更新时间:2023-12-04 11:33:16 25 4
gpt4 key购买 nike

this.editForm = this.fb.group({
step1: this.fb.group({
transport_type_id: ['', [Validators.required]],
flight_code: ['', []],
}),
stops: this.fb.array([
this.initStop() //adds dynamicaly the fields, but I want to watch the whole array
])
});

如果我只想为 step1.transporter_id 设置“valueChanges”,那么这个 observable 工作正常
this.editForm.controls.step1.get('flight_code').valueChanges.subscribe(data => {});

如果我想“观看”“停止:this.fb.array”,语法是什么。

不起作用的例子
this.editForm.controls.stops.get().valueChanges.subscribe(data => {});
this.editForm.controls.stops.get('stops').valueChanges.subscribe(data => {});
this.editForm.get('stops').valueChanges.subscribe(data => {});

最佳答案

您可以订阅整个数组的更改并在数组中查找您的特定对象以执行任何其他操作
假设 'stops' 数组包含这个数组:

stopsList: any[] = [
{
id: 1,
name: 'John'
},
{
id: 2,
name: 'Brian'
}
]
const stopsArray = this.editForm.get('stops') as FormArray;

stopsArray.valueChanges.subscribe(item => {
// THIS WILL RETURN THE ENTIRE ARRAY SO YOU WILL NEED TO CHECK FOR THE SPECIFC ITEM YOU WANT WHEN CHANGED
// This is assuming your group in the array contains 'id'.

if (item.findIndex(x => x.id == 1) != -1) {
console.log('do something');
}
});
如果您希望定位数组中的特定项目并且特定属性的值发生变化,那么这将实现
const stopsArray = this.editForm.get('stops') as FormArray;

const firstID = stopsArray.controls.find(x => x.get('id').value == 1);

firstID.get('name').valueChanges.subscribe(value => {
console.log(value);
});
https://stackblitz.com/edit/angular-subscribe-to-formarray-valuechanges

关于Angular - FormArray 的 valueChanges,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44544989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com