在角度材质2中的md-select中设置默认选项

Lak*_*ngh 2 angular-material2 angular

我试图设置md-selectangular-material2 的默认选项,但无济于事.

form2.component.ts:

export class Form2Component implements OnInit {
    frequency = [
                {"title" : "One Time",         "description" : "", "discount" : {"value" : 0,  "type" : "value"} },
                {"title" : "Weekly",           "description" : "", "discount" : {"value" : 20, "type" : "percent"} },
                {"title" : "Every other Week", "description" : "", "discount" : {"value" : 15, "type" : "percent"} },
                {"title" : "Monthly",          "description" : "", "discount" : {"value" : 10, "type" : "percent"} }
            ]
    constructor(){}
    ngOnInit(){}
}
Run Code Online (Sandbox Code Playgroud)

form2.component.html:

<md-select placeholder="Frequency" [formControl]="userForm.controls['frequency']">
    <md-option *ngFor="let frequ of frequency" [value]="frequ" [selected]="frequ.title == 'Weekly'">{{frequ?.title}}</md-option>
</md-select>
Run Code Online (Sandbox Code Playgroud)

AJT*_*T82 5

由于您使用的是被动表单,因此可以将默认值设置为formcontrol.所以你可以frequency从数组中找到你想要的并将它设置为默认值,如:

this.userForm = this.fb.group({
  frequency: this.frequency.find(x => x.title == 'Weekly')
})
Run Code Online (Sandbox Code Playgroud)

selected从您的模板中删除:

<form [formGroup]="userForm">
  <md-select placeholder = "Frequency" formControlName="frequency" >
    <md-option  *ngFor="let frequ of frequency" [value]="frequ" > {{frequ?.title}} </md-option>
  </md-select>
<form>
Run Code Online (Sandbox Code Playgroud)

演示