可以在AngularDart模板中使用枚举吗?怎么样?

时间:2018-11-14 09:40:43

标签: dart angular-dart

如果我有一个枚举,例如:

@Component(...)
class MyComponent {

    MyEnum myEnum;
    ...
}

如何在模板中使用此枚举?例如

<div *ngIf="myEnum == MyEnum.SOME_OPTION">
    ...
</div>

编辑:我对如何在比较中使用枚举特别感兴趣。

2 个答案:

答案 0 :(得分:1)

来自https://github.com/dart-lang/angular/blob/7f6858bc48c1d2a454a4bc350077d67c277c6516/angular/lib/src/core/metadata.dart#L206-L221

  /// A list of identifiers that may be referenced in the template.
  ///
  /// ## Small Example
  ///
  /// Suppose you want to use an enum value in your template:
  ///
  ///     enum MyEnum { foo, bar, baz }
  ///
  ///     @Component(
  ///       selector: 'example',
  ///       exports: const [MyEnum],
  ///       template: '<p>{{MyEnum.bar}}</p>',
  ///     )
  ///     class Example {}
  ///
  final List<Object> exports;

另请参阅https://github.com/dart-lang/angular/blob/master/angular/CHANGELOG.md#new-features-6

答案 1 :(得分:0)

我找到了办法。我想这有点黑,但是行得通。

为枚举提供一个返回字符串的getter。通过将单引号引起来将模板中的枚举转换为字符串。现在比较两个字符串。

String get choice => myEnum.toString();
...
choice == 'MyEnum.SOME_OPTION'