如何解决Angular:枚举未定义
我正在尝试在angular中使用enum,但是我的enum对象似乎未定义。
枚举
export enum Section {
Equals="Equals",NEquals="NEquals",}
组件
import { Component,OnInit } from '@angular/core';
import { Section } from './model/Section.model';
@Component({
selector: 'app-project'})
export class ProjectComponent implements OnInit {
section = Section;
ngOnInit() {
console.log(this.section);
}
}
当我执行"console.log(this.section)"
时,控制台显示未定义。
有什么解决办法吗?
解决方法
我们使用 TypeScript名称空间将 values()方法添加到Section枚举。
您可以观看现场演示here
section.enum.ts
export enum Section {
Equals = "Equals",NEquals = "NEquals"
}
export namespace Section {
export function values() {
return Object.keys(Section).filter(
type => isNaN(<any>type) && type !== "values"
);
}
}
app.component.ts
import { Component } from "@angular/core";
import { Section } from "./section.enum";
@Component({
selector: "my-app",template: `
<p>
<select>
<option *ngFor="let type of section.values()">
{{ type }}
</option>
</select>
</p>
`
})
export class AppComponent {
section = Section;
ngOnInit() {
console.log(Section);
console.log(Section.Equals);
console.log(Section["Equals"]);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。