Angular Material md-select default selected value

為{幸葍}努か 提交于 2019-12-30 08:01:56

问题


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


回答1:


Use [(ngModel)]:

<mat-select [(ngModel)]="selectedOption">
  <mat-option value="1">One</mat-option>
  <mat-option value="2">Two</mat-option>
</mat-select>

Component:

this.selectedOption = '1';

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:

this.selectedOption = '1';

Note that you can also use it with two-way data binding -> [(value)].

DEMO




回答2:


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

We can easily do it using setting value to default value



来源:https://stackoverflow.com/questions/42148392/angular-material-md-select-default-selected-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!