Angular - 表单数组的valueChanges

时间:2017-06-14 12:35:53

标签: angular angular2-observables 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
        ])
    });

如果我想" valueChanges"对于step1.transporter_id只有这个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 => {});

1 个答案:

答案 0 :(得分:1)

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

假设 'stops' 数组包含这个数组:

list = [1, 2, 3]
list.append(4)
#the list is now [1, 2, 3, 4]
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');
   }
});

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

相关问题