-3

I know you can use a FormControl with an array to build out a multi option MatSelect, but am trying to use FormArrays to handle a multi select. I keep getting errors and after searching Google for a while have ended up with a workaround that just grabs the value from the FormArray, sets it to a FormControl as an array, and then subscribes to that to set the original FormArray value form the FormControl. I don't like this solution though and was wondering if anyone has a working example of how to use a FormArray with a MatSelect

  <mat-select
    multiple
    placeholder="placeholder text"
    [formControlArray]="nameOfFormControlArray">
    <mat-option
      *ngFor="let option of options | keyvalue: originalOrder ; let i = index"
      [value]="option.key === 'true' ? true : (!option.key || option.key === 'false') ? false : option.key"
      [attr.name]="formControlName">
      {{ option.value.name || option.key }}
    </mat-option>
  </mat-select>

1 Answers1

0

Here is the workaround I am using if it helps anyone. I created 'formControl' that is just a regular FormControl. OnInit it is loaded with he saved values and used with the MatSelect. At the same time it's valueChanges is subscribed to and used to populate the formControlArray. The array is cleared each time to remove all the FormControls in it, then each value is pushed in as a new FormControl instance. It isn't super clean, but it works.

      this.formControl.valueChanges.subscribe((values) => {
        formControlArray.clear({ emitEvent: false });

        values.forEach((value) => formControlArray.push(new FormControl(value)));
        this.parentFormGroup.get(this.formControlName).markAsDirty();
      });
    }