首页 > 解决方案 > 如何在 mat-select 中设置模型?

问题描述

我有多个mat-select元素:

<mat-select [formControl]="dropDownControl" multiple></mat-select>

它按类型包含选项元素:

export interface Employee {
    name: string;
    login: string;
}

我尝试使用以下方法选择选项:

ngOnInit() {
  this.dropDownControl.setValue([
        { name: 'aaaa', login: 'aaa_login' },
        { name: 'bbb', login: 'bbb_login' },
   ]);
}

但是选择列表中的选项元素没有被选中(选中),为什么?

标签: angularangular-material

解决方案


使用选项值作为对象时。我们必须使用自定义比较功能来跟踪对象身份。将compareWith与 mat-select 一起使用。

与之比较

将选项值与选定值进行比较的函数。如果它返回 true,则该值将在复选框中被选中。

组件.html

<mat-form-field>
    <mat-select [compareWith]="compareWith" [formControl]="dropDownControl" placeholder="Favorite food" multiple>
        <mat-option *ngFor="let item of items" [value]="item">
            {{item.login}}
        </mat-option>
    </mat-select> 
</mat-form-field>

组件.ts

compareWith(obj1,obj2){
    return obj1 && obj2 && (obj1.login === obj2.login || obj1.name === obj2.name);
  }

工作示例


推荐阅读