0
votes

How can I set as default selected option the first element of the Map I'm using for mat-select? I have:

<mat-select formControlName="formValoreScadenzario" [(value)] ="selectedValoreScadenzario">
  <mat-option *ngFor="let scad of mappaValoriScadenzario" [value]="scad.key">
    {{scad.value}}
  </mat-option>
</mat-select>

where mappaValoriScadenzario is my map. How can I set as default-selected value the first key-value element of my Map? I've only found examples with hardcoded value or with simple arrays of strings.

2

2 Answers

0
votes

you need to fix the default selected in ngOnInit : in your .ts file, take this example -.-,

https://stackblitz.com/edit/how-to-set-default-value-of-mat-select-when-options-are-retriev

0
votes

You should manually set it via setValue method of formValoreScadenzario FormControl after mappaValoriScadenzario initialization (static init or getting data via HttpClient in observable subscription) like this:

this.formValoreScadenzario.setValue(this.mappaValoriScadenzario[0].key)

UPDATE In case of FormControl nested inside FormGroup you can set it value like this:

this.ricercaScadenzarioForm.get('formValoreScadenzario').setValue(this.mappaValoriScadenzario[0].key)

StackBlitz example