角度 6 材质<mat-select>多重使用表单控件设置默认值



我正在使用表单控制,这是我的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)
}
}

我想设置垫选择的默认值,任何帮助如何实现这将是伟大的。我想设置多个默认值。

问题是由于您的选项是对象。为了应用选择,所选对象必须与用于选项的对象相同。修改您的代码如下:

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)
}
}
<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);
}
}

您可以使用mat-selectcompareWith属性。看看答案https://stackoverflow.com/a/57169425/1191125

在使用multiple时使用compareWith函数。

所以HTML看起来像

<mat-form-field>
<mat-select
[compareWith]="compareFn"
[(ngModel)]="theArrayofSelectedValues">
<mat-option  *ngFor="let obj of listOfObjs" [value]="obj">
{{ obj.name }}
</mat-option>
</mat-select>
</mat-form-field>

和TS比较Fn

compareFn(o1: any, o2: any) {
if(o1.id == o2.id )
return true;
}

最新更新