【发布时间】:2019-04-18 02:33:58
【问题描述】:
我有一个带有 Angular Material select component 的简单 Angular 6 应用程序,我想双向绑定到枚举变量。为此,我需要在用于标识选项的字符串值和作为实际 Typescript 类型的枚举值之间进行转换。要将字符串转换为枚举,我总是这样做(假设 Value1 是 MyEnum 的成员):
let s: string = "Value1";
let myEnumVariable: MyEnum = MyEnum[s];
但这似乎不适用于 Angular 模板语句,例如对于以下内容:
app.component.html:
<mat-form-field>
<mat-select placeholder="Select a value" [value]="MyEnum[myVariable]" (valueChange)="myVariable = MyEnum[$event]">
<mat-option value="Value1">Value 1</mat-option>
<mat-option value="Value2">Value 2</mat-option>
</mat-select>
</mat-form-field>
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
public myVariable: MyEnum = MyEnum.Value1;
public MyEnum = MyEnum;
}
enum MyEnum {
Value1,
Value2
}
使用 Angular 开发服务器进行开发时一切正常。但是一旦我运行ng build --prod,就会出现这个错误:
src\app\app.component.html(2,73) 中的错误::类型“字符串”不是 可分配给类型“MyEnum”。
为什么这会出现在建筑中而不是开发中?知道如何在不使用模板语句中的显式方法调用的情况下解决此问题吗?
非常感谢!
PS 我使用的是 Typescript 2.7.2
【问题讨论】:
-
(change)="myVariable = $any(MyEnum[$event]);" -
@yurzui 这解决了它!但是 VS 代码中的 Angular 给出了一个静态检查错误 - [Angular] Unknown method '$any'。有什么办法可以去掉?如果您希望您可以将此作为答案发布,我可以将其标记为已接受:)
-
看起来 Angular 语言服务还不支持 $any 但 AOT 支持 angular.io/guide/aot-compiler#disabling-type-checking-using-any
-
这就是它在aot中不起作用的原因。 stackblitz.com/edit/angular-bpgmal?file=src/app/… AOT 将
$event处理为any。 -
您可以尝试的另一个选项是
(change)="myVariable = MyEnum['' + $event];"
标签: angular typescript angular-material angular-template