Here is the solution
import { Component } from '@angular/core';
interface Food {
value: string;
viewValue: string;
}
interface Car {
value: string;
viewValue: string;
}
/**
* @title Basic select with initial value and no form
*/
@Component({
selector: 'select-initial-value-example',
templateUrl: 'select-initial-value-example.html',
})
export class SelectInitialValueExample {
foods: Food[] = [
{ value: 'steak-0', viewValue: 'Steak' },
{ value: 'pizza-1', viewValue: 'Pizza' },
{ value: 'tacos-2', viewValue: 'Tacos' }
];
cars: Car[] = [
{ value: 'ford', viewValue: 'Ford' },
{ value: 'chevrolet', viewValue: 'Chevrolet' },
{ value: 'dodge', viewValue: 'Dodge' }
];
selectedFood = this.foods[2].value;
selectedCar = this.cars[0].value;
selectCar(event: Event) {
this.selectedCar = (event.target as HTMLSelectElement).value;
}
}
In template use it lie this
<h4>Basic mat-select with initial value</h4>
<mat-form-field appearance="fill">
<mat-label>Favorite Food</mat-label>
<mat-select [(value)]="selectedFood">
<mat-option></mat-option>
<mat-option [value]="option.value" *ngFor="let option of foods">{{ option.viewValue }}</mat-option>
</mat-select>
</mat-form-field>
<p>You selected: {{selectedFood}}</p>
<h4>Basic native select with initial value</h4>
<mat-form-field appearance="fill">
<mat-label>Favorite Car</mat-label>
<select matNativeControl (change)="selectCar($event)">
<option value=""></option>
<option *ngFor="let option of cars" [value]="option.value" [selected]="selectedCar === option.value">{{
option.viewValue }}</option>
</select>
</mat-form-field>
<p>You selected: {{selectedCar}}</p>