Angular - 表单数组的valueChanges

Mic*_*lis 5 angular2-observables angular angular-reactive-forms

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
        ])
    });
Run Code Online (Sandbox Code Playgroud)

如果我想为step1.transporter_id"valueChanges",那么这个observable工作正常

this.editForm.controls.step1.get('flight_code').valueChanges.subscribe(data => {});
Run Code Online (Sandbox Code Playgroud)

如果我想"观察""stops: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 => {});
Run Code Online (Sandbox Code Playgroud)

Bri*_*ith 2

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

假设“stops”数组包含以下数组:

stopsList: any[] = [
 {
   id: 1,
   name: 'John'
 },
 {
   id: 2,
   name: 'Brian'
 }
]
Run Code Online (Sandbox Code Playgroud)
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');
   }
});
Run Code Online (Sandbox Code Playgroud)

如果您希望定位数组中的特定项目并且特定属性的值发生变化,那么这将实现这一目标

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);
});
Run Code Online (Sandbox Code Playgroud)

https://stackblitz.com/edit/angular-subscribe-to-formarray-valuechanges