首页 > 解决方案 > Angular:mat-select的2路绑定不起作用,在代码中分配值会导致它在UI中重置

问题描述

我正在尝试将 mat-select 绑定到这样的枚举值:

<mat-form-field>
  <mat-label>Type</mat-label>
  <mat-select [(ngModel)]="selectedType" [compareWith]="compareType">
    <mat-select-trigger>
      {{types[selectedType]?.name}}
    </mat-select-trigger>
    <mat-option *ngFor="let type of types | keyvalue" [value]="type.key">
      <mat-icon>{{type.value.icon}}</mat-icon> {{type.value.name}}
    </mat-option>
  </mat-select>
</mat-form-field>

和打字稿:

enum Type {
  Hardware = 0,
  Software = 1
}

types: { [TP in number]: { icon: string, name: string }; } = {
  [Type.Hardware]: { icon: 'computer', name: 'Hardware' },
  [Type.Software]: { icon: 'keyboard', name: 'Software' },
};

selectedType: Type;

compareType(type1: Type, type2: Type): boolean {
  return ((type1 as Type) === (type2 as Type));
}

我希望将 select 的值绑定到selectedType,我正在尝试使用[(ngModel)]="selectedType" [compareWith]="compareType".

问题是,这种数据绑定并没有完全双向。当我使用 UI 分配值时,绑定会相应更新,但是当我更新代码中的值时,它会重置 UI 中的值,再次显示占位符。但是,虽然 UI 无法正确显示,但该值已正确分配。

标签: angulartypescript2-way-object-databinding

解决方案


您的代码中存在类型不匹配问题。

selectedTypeType一个数字类型。

[value]="type.key"你在 哪里设置

<mat-option *ngFor="let type of types | keyvalue" [value]="type.key">

type.key由于keyvalue管道是一个字符串。

在上面的代码中,当您从下拉列表中选择一个项目时,将字符串值“0”或“1”分配给selectedType. 如果您以编程方式分配一个值,例如分配一个this.selectedType = Type.Hardware数字值0selectedType

并且由于您的compareType函数使用严格相等(===) 它返回 false 因为1 === "1"false

你可以;

  • 让你enum Type有字符串值;
enum Type {
  Hardware = "0",
  Software = "1"
}
  • 或者,type.key在绑定到时转换为数字mat-option
[value]="+type.key"
  • 或者,在函数中使用相等(==) 而不是严格相等(===) compareType。(我个人不推荐这个!)
  compareType(type1: Type, type2: Type): boolean {
    return ((type1 as Type) == (type2 as Type));
  }

这是一个工作演示


推荐阅读