Combining Angular's FormBuilder with async code (Observables)

212 Views Asked by At

I have an array of Observables which I'm displaying via Angular's async pipe in a form. The devices$ array is dynamic, I'm adding elements to it via button click.

<form [formGroup]="devices_form" (ngSubmit)="submitForm()">
   <div *ngFor="let device of devices$">
      <div *ngIf="device | async as device">
        <input value="{{ device.name }}">
        <input value="{{ device.type }}">
      </div>
    </div>
</form>

I now need to submit the data (name etc.) of devices$ via Angular's FormBuilder. I guess I need to first map / iterate the devices$ array, subscribe to its elements and push the results to a FormGroup field.

Although I'm confused because my Observables are async of course and when submitting the form I have to make sure that my data is "complete", if that makes any sense. Until now I do not manually subscribe to the Observables in my TypeScript code.

Here's my simplified code:

// Interface of device
export interface Device {
 name: string,
 type: string
}

// Devices form I need to submit
this.devices_form = this.formBuilder.group({
   devices: ['', Validators.required]
});

// Submit form if valid
submitForm() {

   // I guess I need to set the devices value here
   this.devices_form.get('devices').setValue('array data here...');

   if (this.devices_form.valid) {
      this.saveData(this.devices_form.value);
   }
}

I already tried mapping devices$, subscribing to its elements and adding this to the FormGroup. Although, since it's async data, it didn't work properly (because a Subscription is never 'finished', I didn't receive the correct amount of elements). I also played around with FormArray (from Angular) but wasn't successful.

Does anybody know how to combine async code with an array of Observables and Angular's FormBuilder?

Thank you in advance!

0

There are 0 best solutions below