Search code examples
angulartypescriptangular-material2

Angular Material: mat-select not selecting default


I have a mat-select where the options are all objects defined in an array. I am trying to set the value to default to one of the options, however it is being left selected when the page renders.

My typescript file contains:

  public options2 = [
    {"id": 1, "name": "a"},
    {"id": 2, "name": "b"}
  ]
  public selected2 = this.options2[1].id;

My HTML file contains:

  <div>
    <mat-select
        [(value)]="selected2">
      <mat-option
          *ngFor="let option of options2"
          value="{{ option.id }}">
        {{ option.name }}
      </mat-option>
    </mat-select>
  </div>

I have tried setting selected2 and the value in mat-option to both the object and its id, and have tried using both [(value)] and [(ngModel)] in the mat-select, but none are working.

I am using material version 2.0.0-beta.10


Solution

  • Use a binding for the value in your template.

    value="{{ option.id }}"
    

    should be

    [value]="option.id"
    

    And in your selected value use ngModel instead of value.

    <mat-select [(value)]="selected2">
    

    should be

    <mat-select [(ngModel)]="selected2">
    

    Complete code:

    <div>
      <mat-select [(ngModel)]="selected2">
        <mat-option *ngFor="let option of options2" [value]="option.id">{{ option.name }}</mat-option>
      </mat-select>
    </div>
    

    On a side note as of version 2.0.0-beta.12 the material select now accepts a mat-form-field element as the parent element so it is consistent with the other material input controls. Replace the div element with mat-form-field element after you upgrade.

    <mat-form-field>
      <mat-select [(ngModel)]="selected2">
        <mat-option *ngFor="let option of options2" [value]="option.id">{{ option.name }}</mat-option>
      </mat-select>
    </mat-form-field>