angular - 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 无法正确显示,但该值已正确分配。
解决方案
您的代码中存在类型不匹配问题。
selectedType
有Type
一个数字类型。
[value]="type.key"
你在 哪里设置
<mat-option *ngFor="let type of types | keyvalue" [value]="type.key">
type.key
由于keyvalue
管道是一个字符串。
在上面的代码中,当您从下拉列表中选择一个项目时,将字符串值“0”或“1”分配给selectedType
. 如果您以编程方式分配一个值,例如分配一个this.selectedType = Type.Hardware
数字值0
selectedType
并且由于您的compareType
函数使用严格相等(===) 它返回 false 因为1 === "1"
是false
你可以;
- 让你
enum Type
有字符串值;
enum Type {
Hardware = "0",
Software = "1"
}
- 或者,
type.key
在绑定到时转换为数字mat-option
[value]="+type.key"
compareType(type1: Type, type2: Type): boolean {
return ((type1 as Type) == (type2 as Type));
}
这是一个工作演示
推荐阅读
- sql-server - 如何在 SQL Server 2012 中的普通存储过程中找出存储过程名称
- mongodb - MongoDB查询以使用公式更新集合中文档的每个字段
- spring-mvc - 仅在登录后创建 Spring Mvc 会话
- c++ - arduino 中函数和打印函数值的问题
- java - 模型无法转换为 ModelRealmProxyInterface
- typescript - Vue Cli 3 - Typescript - Vuetify 样式不适用于带有 @WithRender 的单独模板文件
- javascript - 编码 % 以传入 URL javascript
- angular - 我们如何使用 angular4 或 angular4+ 从 MySql 渲染任何类型的数据(ID、Image、Description、ImageId)?
- android - 使用 okhttp 多部分将图像从 Android 上传到服务器
- azure-data-factory-2 - 数据工厂自定义活动 (ADF V2) 中的并行任务