我正在使用表单控件,这是我的html组件的代码
<mat-form-field>
<mat-select placeholder="Toppings" [formControl]="toppings" multiple>
<mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping.value}}</mat-option>
</mat-select>
</mat-form-field>
我的ts文件是
export class SelectMultipleExample {
toppings = new FormControl();
toppingList: any[] = [
{ id:1,value:"test 1"},
{ id:2,value:"test 2"},
{ id:3,value:"test 4"},
{ id:4,value:"test 5"},
{ id:5,value:"test 6"},
{ id:6,value:"test 7"}
];
constructor(){
this.bindData();
}
bindData(){
const anotherList:any[]=[
{ id:1,value:"test 1"},
{ id:2,value:"test 2"}
]
this.toppings.setValue(anotherList)
}
}
我想为mat select设置默认值,如何实现这一点的任何帮助都会很棒。我想设置多个默认值。
答案 0 :(得分:3)
问题是由于您的选项是对象这一事实。为了应用选择,所选对象必须是与用于选项的对象相同的对象。修改您的代码,如下所示:
export class SelectMultipleExample {
toppings = new FormControl();
toppingList: any[] = [
{ id:1,value:"test 1"},
{ id:2,value:"test 2"},
{ id:3,value:"test 4"},
{ id:4,value:"test 5"},
{ id:5,value:"test 6"},
{ id:6,value:"test 7"}
];
constructor(){
this.bindData();
}
bindData() {
const anotherList: any[] = [
this.toppingList[0],
this.toppingList[1]
]
this.toppings.setValue(anotherList)
}
}
答案 1 :(得分:0)
<mat-form-field>
<mat-label>Select Global Markets</mat-label>
<mat-select [formControl]="globalmarketCategory" multiple >
<mat-option *ngFor="let list of toppingList" [value]="list">{{list.value}}</mat-option>
</mat-select>
export class SelectMultipleExample {
globalmarketCategory= new FormControl();
toppingList: any[] = [
{ id:1,value:"test 1"},
{ id:2,value:"test 2"},
{ id:3,value:"test 4"},
{ id:4,value:"test 5"},
{ id:5,value:"test 6"},
{ id:6,value:"test 7"}
];
list = []
constructor(){
const anotherList:any[]=[
{ id:1,value:"test 1"},
{ id:2,value:"test 2"}
]
this.globalmarketCategory.setValue(anotherList);
}
}
答案 2 :(得分:0)
您可以使用compareWith
的{{1}}属性。看到答案https://stackoverflow.com/a/57169425/1191125