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 => {});
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With