I have a simple select option form field in my Angular material project:
component.html
HTML
<mat-form-field>
<mat-select [(ngModel)]="modeSelect" placeholder="Mode">
<mat-option *ngFor="let obj of Array" [value]="obj.value">{{obj.value}}</mat-option>
</mat-select>
Now set your default value to
modeSelect
, where you are getting the values in Array variable.
It took me several hours to figure out this until the similarity of the datatypes between the array and that of the default value worked for me...
Working StackBlitz
No need to use ngModel
or Forms
In your html:
<mat-form-field>
<mat-select [(value)]="selected" placeholder="Mode">
<mat-option value="domain">Domain</mat-option>
<mat-option value="exact">Exact</mat-option>
</mat-select>
</mat-form-field>
and in your component just set your public property selected
to the default:
selected = 'domain';
I was able to set the default value or whatever value using the following:
Template:
<mat-form-field>
<mat-label>Holiday Destination</mat-label>
<mat-select [(ngModel)]="selectedCity" formControlName="cityHoliday">
<mat-option [value]="nyc">New York</mat-option>
<mat-option [value]="london">London</mat-option>
<mat-option [value]="india">Delhi</mat-option>
<mat-option [value]="Oslo">Oslo</mat-option>
</mat-select>
</mat-form-field>
Component:
export class WhateverComponent implements OnInit{
selectedCity: string;
}
ngOnInit() {
this.selectedCity = 'london';
}
}
I would like to add to Narm's answer here and have added the same as a comment under her answer.
Basically the datatype of the value assigned to [(value)] should match the datatype of the [value] attribute used for the mat-options. Especially if some one populates the options using an *ngFor as below
<mat-form-field fxHide.gt-sm='true'>
<mat-select [(value)]="heroes[0].id">
<mat-option *ngFor="let hero of heroes" [value]="hero.id">{{ hero.name }}</mat-option>
</mat-select>
</mat-form-field>
Notice that, if you change the [(value)]="heroes[0].id" to [(value)]="heroes[0].name" it won't work as the data types don't match.
These are my findings, please feel free to correct me if needed.