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 => {});
3
  • 1
    In my plunker plnkr.co/edit/Kc9KiIiMN5w5sUqKVUJo?p=preview it works Commented Jun 14, 2017 at 12:46
  • 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... Commented Jun 14, 2017 at 12:54
  • Did you manage to fix it? I have the same problem. Commented Jul 30, 2020 at 19:36

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.