问题是由于你的选项是对象。为了应用选择,所选对象必须与选项中使用的对象相同。按如下方式修改您的代码:
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);
}
}
使用多个时使用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;
}
G给出的答案。 Tranter 给出了正确答案。
根据他们的回答,我创建了以下更详细的示例(可能更接近此功能的实际实现):
toppings.html:
<mat-form-field>
<mat-label>Select Your Favorite Topping(s)</mat-label>
<mat-select placeholder="Select Topping(s)" [formControl]="ToppingsControl" required multiple>
<mat-option *ngFor="let t of AllToppings" [value]="t">{{t.Name}}</mat-option>
</mat-select>
</mat-form-field>
toppings.ts:
import { Component } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import ITopping from 'src/app/interfaces/topping-dto';
@Component({
selector: 'toppings',
templateUrl: './toppings.html',
styleUrls: ['./toppings.css']
})
export default class SelectMultipleExample {
protected ToppingsControl: FormControl<Array<ITopping>> = new FormControl(null, Validators.required);
protected AllToppings: Array<ITopping> = [];
public constructor() {
// These values can be injected, pulled from a database, etc.
this.AllToppings.push({ Id: 1, Name: 'Sprinkles' });
this.AllToppings.push({ Id: 2, Name: 'Hot Fudge' });
this.AllToppings.push({ Id: 3, Name: 'Whipped Cream' });
this.AllToppings.push({ Id: 4, Name: 'Crushed Nuts' });
this.AllToppings.push({ Id: 5, Name: 'Maraschino cherries' });
// Get a reference to the objects that are initially selected by default
let selectedToppings: Array<ITopping> = [
this.AllToppings[0],
this.AllToppings[1]
];
// Set the value of the control to be the selected objects
this.ToppingsControl.setValue(selectedToppings);
}
}
topping-dto.ts:
interface ITopping {
Id: number,
Name: string
}
export default IClientDto;