Peter
Peter

Reputation: 1710

mat-select with an initial value

Given the following Angular component that uses mat-select

export enum AllValues {
  VALUE_A = "A",
  VALUE_B = "B",
  VALUE_C = "C",
}

@Component({
  selector: 'my-app',
  template: `
    <mat-form-field>
      <mat-select ([ngModel])="myValue">
        <mat-option *ngFor="let o of valueOptions" value="{{o}}">{{o}}</mat-option>
      </mat-select>
    </mat-form-field>
    <p> Selected value: {{myValue}} </p>
    `,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  myValue: AllValues = AllValues.VALUE_B;
  valueOptions = Object.keys(AllValues);
}

How can I have the initial value for myValue be displayed in the mat-select in the UI? The value is not being shown with the current state of the code.

Follow this StackBlitz link for the full code and a running demo.

Upvotes: 3

Views: 11451

Answers (1)

Vivek Doshi
Vivek Doshi

Reputation: 58523

Issue :

Here ngModel value and select option value both are different , that's the reason you are not getting selected value


Component Side :

// add this line
allValues = AllValues;

Template side :

// Change ([ngModel]) to [(ngModel)]
<mat-select [(ngModel)]="myValue">
    // value={{o}} to value="{{allValues[o]}}"
    <mat-option *ngFor="let o of valueOptions" value="{{allValues[o]}}">{{o}}</mat-option>

WORKING DEMO

Upvotes: 5

Related Questions