Angular - valueChanges for FormArray
Asked Answered
C

1

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
        ])
    });

If I want to "valueChanges" for the step1.transporter_id only then this observable works fine

this.editForm.controls.step1.get('flight_code').valueChanges.subscribe(data => {});

What is the syntax if I want to "watch" the "stops: this.fb.array".

Examples that don't work

this.editForm.controls.stops.get().valueChanges.subscribe(data => {});
this.editForm.controls.stops.get('stops').valueChanges.subscribe(data => {});
this.editForm.get('stops').valueChanges.subscribe(data => {});
Ceremony answered 14/6, 2017 at 12:35 Comment(3)
In my plunker plnkr.co/edit/Kc9KiIiMN5w5sUqKVUJo?p=preview it worksAcrobatic
The problem with that "this.editForm.get('stops').valueChanges" is that it fires everytime.... But if i remove "this.initStop() from the form then it works. The is a connection between them...Ceremony
Did you manage to fix it? I have the same problem.Rank
K
2

You can subscribe to the entire array's changes and look for your specific object in the array to do any additional actions

Assuming the 'stops' array contains this array:

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');
   }
});

If you are looking to target a specific item in the array and a specific property's value changes then this will get achieve that

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

Kith answered 26/6, 2021 at 1:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.