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, none of them helped.
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';
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)] .
<mat-select [value]="0" >
我们可以很容易地使用将值设置为默认值来做到这一点
According to documentation you can do by the following way.
Option:1
<md-select value={{ defaultValue }}>
<md-option value="{{ defaultValue }}">{{defaultValue}}</md-option>
<md-option value="1">One</md-option>
<md-option value="1">One</md-option>
<md-option value="2">Two</md-option>
</md-select>
Option:2
<md-select value="None">
<md-option value="None">None</md-option>
<md-option value="1">One</md-option>
<md-option value="1">One</md-option>
<md-option value="2">Two</md-option>
</md-select>
It must any value of select dropdown. Else it will not work.
<mat-select formControlName="timezone" required [(ngModel)]="selectedOption">
<mat-option *ngFor="let item of array" [value]="item.value">{{item.name}}</mat-option>
</mat-select>
for correct working need binding of value [value]
or it don't work
If you are using Reactive Forms, you can do it this way:
In your template:
<mat-form-field>
<mat-label>Sexo</mat-label>
<mat-select [formControlName]="'sex'" #sexField>
<mat-option value="2">Masculino</mat-option>
<mat-option value="1">Femenino</mat-option>
<mat-option value="3">Otro</mat-option>
</mat-select>
</mat-form-field>
and in your component:
form: FormGroup;
constructor(private _formBuilder: FormBuilder) {
}
ngOnInit() {
this.form = this._formBuilder.group({
sex: ['2'], // set default option
});
if (weAreEditing) {
this.form.controls['sex'].setValue(edit.sex.id + ''); // set the option that you want
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.