Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material md-select default selected value

Tags:

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

like image 864
ErnieKev Avatar asked Feb 09 '17 22:02

ErnieKev


People also ask

How to set selected value of dropdown in angular material?

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.

How do I change the default value for Maryland select?

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.

How do I set default value in Ng?

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.


2 Answers

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

like image 176
developer033 Avatar answered Sep 19 '22 13:09

developer033


 <mat-select [value]="0" >

We can easily do it using setting value to default value

like image 23
Vikram Jangra Avatar answered Sep 19 '22 13:09

Vikram Jangra