3

I am trying to figure out how to display a mat-select in a dialog and have some of the mat-options preselected. I've created a simple example to demonstrate what I want to do:

StackBlitz

In my example, I want to display a selectable list of colors, with a few of the colors preselected. I first create a mat-select and its contents (mat-options) by iterating over an array of strings in my dialog's TS file:

<mat-select placeholder="Colors" formControlName="selectedColors" multiple>
   <mat-option *ngFor="let color of allColors" value="{{color}}">{{color}}</mat-option>
</mat-select>

This works just fine. In my dialog's TS file, I have the following arrays declared:

this.allColors =  ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
this.defaultSelections = ['red', 'green', 'blue'];

Note the 2nd array, "defaultSelections": I want to have these items pre-selected when the dialog is displayed. I can't seem to find / figure out how to do this.

Thank you in advance for the help!

  • 2
    just, when create the form use this.form = this.formBuilder.group({ selectedColors: [this.defaultSelections] });. Mat-select with multiple expect an array with the values of the selections. Yes! a FormControl can be store an array, an object, a string... – Eliseo Feb 26 '19 at 15:12
  • 2
    Yes as like Eliseo said, you are alright just need to put the word inside the [] like ```selectedColors: [this.defaultSelections]``` instead of ```selectedColors: []``` .. Working example https://stackblitz.com/edit/angular-material-w7eclt – Maniraj Murugan Feb 26 '19 at 15:29
  • 1
    I figured it was something as simple as that, but I was obviously looking in the wrong place. Thank you! – James A Cubeta Feb 26 '19 at 15:34

1 Answers1

1

Since you're using ReactiveForms you can use the default value property on FormControl to set the initial values of mat-select.

this.defaultSelections = ['red', 'green', 'blue'];

this.form = this.formBuilder.group({
  selectedColors: [this.defaultSelections]
});

A working example.

VascoCC
  • 480
  • 6
  • 17
  • How can I use this in array containing objects in which each object have id? Do I store object in the formbuilder array or just the object ids? – S. Karki Jan 19 '22 at 06:41