Angular Material Mat-select not working properly

angularangular-material

I am trying to use latest angular material. I am stuck at mat-select component.
Here is my html.

    <mat-form-field>
    <mat-select placeholder="Favorite food" [(value)]="selectedLevel">
      <mat-option *ngFor="let food of foods" [value]="food.value">
        {{food.viewValue}}
      </mat-option>
    </mat-select>
  </mat-form-field>

Options are populated properly but when i select one option then there is no select value in mat-select element, it is blank. But when i tried to inspect in browser, the required element exists when was hidden in UI

<span class="ng-tns-c4-1 ng-star-inserted">Steak</span>

What might be the missing thing here, anyone can you please help me ?

Best Answer

You need to read the selected value back in the component, do not try to parse the HTML looking for it. You are binding the value using [(selectedLevel)] so selectedLevel in your component has the selected value of that select.

See stackblitz


select-overview-example.html

<h4>Basic mat-select</h4>
<mat-form-field>
  <mat-select placeholder="Favorite food" name="foods" [(value)]="selectedFood">
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{food.viewValue}}
    </mat-option>
  </mat-select>
</mat-form-field>
<p>Selected food = {{selectedFood}}</p>

<h4>Basic mat-select with ngModel</h4>
<mat-form-field>
  <mat-select placeholder="Favorite food" name="foods2" [(ngModel)]="selectedFoodModel">
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{food.viewValue}}
    </mat-option>
  </mat-select>
</mat-form-field>

<p>Selected food = {{selectedFoodModel}}</p>

component.ts

import {Component, OnInit} from '@angular/core';

export interface Food {
  value: string;
  viewValue: string;
}

@Component({
  selector: 'select-overview-example',
  templateUrl: 'select-overview-example.html',
  styleUrls: ['select-overview-example.css'],
})
export class SelectOverviewExample implements OnInit {
  selectedFood: string;
  selectedFoodModel: string;
  foods: Food[] = [
    {value: 'steak-0', viewValue: 'Steak'},
    {value: 'pizza-1', viewValue: 'Pizza'},
    {value: 'tacos-2', viewValue: 'Tacos'}
  ];

  ngOnInit(){
    this.selectedFood = this.foods[1].value;
    this.selectedFoodModel = this.foods[1].value;
  }
}
Related Topic