Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - valueChanges for FormArray

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 => {});
like image 246
Michalis Avatar asked Jun 14 '17 12:06

Michalis


People also ask

How does Angular define FormArray?

First, we need to import the FormArray from the Angular Forms Module. Build a formGroup orderForm using the FormBuilder. We define items as FormArray. We need to capture two fields under each item, the name of the item & description and price.

How do I validate FormArray controls?

Validating Angular FormArray First you need to add the required validators while creating a new product form group inside the addProduct method. Now let's add a span element adjacent to the input control. Add the following CSS to the app. component.


1 Answers

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

like image 92
Brian Smith Avatar answered Nov 15 '22 01:11

Brian Smith