Home > OS >  Populate Angular formGroup from many observables
Populate Angular formGroup from many observables

Time:05-20

I have a postcode$ observable and want to populate the postalCode form input with its value when I create the form group using this.customerForm = this.formBuilder.group({}).

This SO post answer suggests initialising the form in a subscribe of the observable:

ngOnInit() {
    // ...
    // .take(2) to ensure that it will run only for the first value:
    contactsObservable.take(1).subscribe(contacts => {
        this.form = this.fb.group({contact: [this.contacts[0], Validators.required]];
    });
    // ...
}

However, my form has a lot of different fields which need populating from various observables...

  initForm = () => {
    this.myForm = this.form.group({
      postCode: ['', Validators.required],
      // ...many other fields...
    });
  };

Is it possible to populate the '' directly from the observable? If so, I can simply pass in the numerous observable values into the one form group builder.

CodePudding user response:

One way to solve this is by using forkJoin to combine all your observables.

Basically, this function takes an array of observables, when all are completed, then the emitted values are combined and returned in an array in the same order as your array of observables, more details here.

import { forkJoin } from 'rxjs';

const observables: Array<Observable<TA | TB | TC>> = [observableA$, observableB$, observableC$]; // N quantity of observables

forkJoin(observables).subscribe((responseData: Array<TA | TB | TC>) => {
  this.myForm = this.form.group({
    firstField: [responseData[0] as TA, [Validators.required]],
    secondField: [responseData[1] as TB, [Validators.required]],
    thirdField: [responseData[2] as TC, [Validators.required]],
  });
});
  • Related