Lin*_* Vu 17 html enums typescript angular
如何在 Angular 8 模板中使用枚举?
组件.ts
import { Component } from '@angular/core';
import { SomeEnum } from './global';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = SomeEnum.someValue;
}
Run Code Online (Sandbox Code Playgroud)
组件.html
<span *ngIf="name === SomeEnum.someValue">This has some value</value>
Run Code Online (Sandbox Code Playgroud)
这目前不起作用,因为模板没有引用SomeEnum
. 我该如何解决?
ERROR Error: Cannot read property 'someValue' of undefined
Jor*_*ato 30
在 TS
public get SomeEnum() {
return SomeEnum;
}
Run Code Online (Sandbox Code Playgroud)
在 HTML 中使用
*ngIf="SomeEnum.someValue === 'abc'"
Run Code Online (Sandbox Code Playgroud)
小智 17
我认为如果您不想用不必要的逻辑使您的类膨胀,这将是更简单的解决方案之一。我会避免调用函数来返回枚举,因为它会在每次重新渲染时被调用,并且如果大量使用它会影响您的性能。
public readonly myEnum : typeof MyEnum = MyEnum;
Run Code Online (Sandbox Code Playgroud)
Sid*_*era 15
您必须首先将其声明为属性:
import { Component } from '@angular/core';
import { SomeEnum } from './global';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = SomeEnum.someValue;
importedSomeEnum = SomeEnum;
}
Run Code Online (Sandbox Code Playgroud)
然后在模板中使用它:
<span *ngIf="name === importedSomeEnum.someValue">This has some value</span>
Run Code Online (Sandbox Code Playgroud)
这是供您参考的工作演示。
您可以将等于SomeEnum
枚举的字段(它可以从另一个文件导入)声明为组件文件中的公共类字段。然后它将可以在模板中访问。
// component
export class AppComponent {
name = SomeEnum.someValue;
enum = SomeEnum;
}
// template
<span *ngIf="name === enum.someValue">This has some value</value>
Run Code Online (Sandbox Code Playgroud)
小智 5
是的,模板不能直接引用枚举。有几种方法可以做到这一点。1. 将 Enum 引用添加到组件 ts 文件中,如下所示
someEnum = SomeEnum;
Run Code Online (Sandbox Code Playgroud)
然后您将能够像这样使用模板中的引用
<span *ngIf="name === someEnum.someValue">This has some value</value>
Run Code Online (Sandbox Code Playgroud)
<span *ngIf="checkCondition(name)">This has some value</value>
归档时间: |
|
查看次数: |
10022 次 |
最近记录: |