我正在尝试在angular-material2的md-select
中设置默认选项,但无济于事。
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(){}
}
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>
答案 0 :(得分:5)
由于您使用的是被动表单,因此可以将默认值设置为formcontrol。所以你可以从数组中找到你想要的frequency
并将其设置为默认值,如:
this.userForm = this.fb.group({
frequency: this.frequency.find(x => x.title == 'Weekly')
})
从模板中移除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>
<强> Demo 强>
答案 1 :(得分:1)
组件HTML
<md-select placeholder="Favorite food" [(ngModel)]="selectedValue" name="food">
<md-option *ngFor="let food of foods" [value]="food.value" >
{{food.viewValue}}
</md-option>
</md-select>
<p> Selected value: {{selectedValue}} </p>
Component.ts
@Component({
selector: 'select-form-example',
templateUrl: './select-form-example.html',
})
export class SelectFormExample {
foods = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'}
];
// setting this is the key to initial select.
selectedValue: string = this.foods[0].value;
将所选值设置为您希望它为默认值的数组中的值,您不使用双向绑定
答案 2 :(得分:0)
在md-option值中使用对象时,默认值的对象引用和选项列表中的相应选项是不等于。
要解决此问题,您需要在设置FormGroup 之前使用选项列表中的相应选项覆盖默认值。
以下是一个例子:
<强> my.component.ts 强>
export class MyComponent implements OnInit {
myobject: Object = {id:'1323', label:'myform', service: {id:'S01', label:'Service 01': desc:''}}
services: Array<Service> = [
{id:'S01', label:'Service 01' , desc:'Service desc'},
{id:'S02', label:'Service 02' , desc:'Service desc'},
{id:'S03', label:'Service 03' , desc:'Service desc'}];
myForm : FormGroup;
constructor(private fb: FormBuilder) {
// Override the service in myobject before setting the FormGroup myForm
this.services.forEach(srv => {
// Compare service By id
if (srv.id === myobject.service.id) {
myobject.service = srv;
}
});
// Set the formGroup with the myobject containing the good reference to the services array.
this.myForm = this.fb.group(myobject);
}
}
<强> my.component.html 强>
<md-select class="carrier-select form-control" formControlName="service">
<md-option class="carrier-option" *ngFor="let service of services" [value]="service">{{service.label}}</md-option>
</md-select>