7
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 => {});
4

1 回答 1

1

您可以订阅整个数组的更改并在数组中查找您的特定对象以执行任何其他操作

假设 '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

于 2021-06-26T01:24:13.733 回答