I am using Angular 2 with Angular Material. Looking at the documentation, I am trying to get the select to have a default value as oppose to an empty place holder.
I have tried the following two options and both of them does not set a default value
<md-select selected="1"> <md-option value="1" >One</md-option> <md-option value="2">Two</md-option> </md-select> <md-select> <md-option value="1" selected="true">One</md-option> <md-option value="2">Two</md-option> </md-select>
I looked at all the documentations and the examples, non of them helped
Angular Material Select is created using <mat-select> which is a form control for selecting a value from a set of options. To add elements to Select option, we need to use <mat-option> element and to bind value with <mat-option> , use value property of it.
When applied, md-option-empty will mark the option as "empty" allowing the option to clear the select and put it back in it's default state. You may supply this attribute on any option you wish, however, it is automatically applied to an option whose value or ng-value are not defined.
In my opinion the correct way to set a default value is to simply pre-fill your ng-model property with the value selected from your ng-options , angular does the rest. Essentially when you define the $scope property your select will bind to assign it the default value from your data array.
Use [(ngModel)]
:
<mat-select [(ngModel)]="selectedOption"> <mat-option value="1">One</mat-option> <mat-option value="2">Two</mat-option> </mat-select>
Component:
selectedOption = '1';
DEMO
Edit #1:
Since Material2.0.0#beta10 (specifically this PR) you can select a value using the value
property of MatSelect
:
<mat-select [value]="selectedOption"> <mat-option value="1">One</mat-option> <mat-option value="2">Two</mat-option> </mat-select>
Component:
selectedOption = '1';
Note that you can also use it with two-way data binding -> [(value)].
DEMO
<mat-select [value]="0" >
We can easily do it using setting value to default value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With