如何在Angular 2模板中使用枚举

Pre*_*har 32 angular

我试图在angularjs 2模板中使用枚举.以下是我的代码

@Component({
    selector: 'test',
    template: `
<ul class="nav navbar-nav">
    <li class="{{activeSection == SectionType.Primary ? 'active': ''}}"><a href="javscript:void(0);" (click)="setActiveSection(SectionType.Primary)">Primary Details</a></li>
    <li class="{{activeSection == SectionType.Aditional ? 'active': ''}}"><a href="javscript:void(0);" (click)="setActiveSection(SectionType.Aditional)">Additional Details</a></li>
    <li class="{{activeSection == SectionType.Payment ? 'active': ''}}"><a href="javscript:void(0);" (click)="setActiveSection(SectionType.Payment)">Payment Settings </a></li>           
  </ul>`
  })
  export class TestComponent{
  activeSection: SectionType = SectionType.Primary;
   setActiveSection(section: SectionType) {
        this.activeSection = section;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的枚举:

enum SectionType {
    Primary,
    Aditional,
    Payment
}
Run Code Online (Sandbox Code Playgroud)

抛出EXCEPTION:TypeError:无法读取未定义的属性"Primary"

jky*_*sey 21

在模板中使用Enum的简单方法是

@Component(...)
export class MyComp {
  public MyEnum: any = MyEnum;
}
Run Code Online (Sandbox Code Playgroud)

然后在模板中:

<select>
  <option value="MyEnum.ValueA">Value A</option>
</select>
Run Code Online (Sandbox Code Playgroud)

  • `MyEnum: typeof MyEnum = MyEnum;`:) (8认同)
  • @FerranMaylinch 我认为这没有必要,因为你现在可以执行 `MyEnum = MyEnum;` 并且它编译得很好。一定是围绕 Angular 8 的 TS 版本进行了更改。 (2认同)

Thi*_*ier 14

SectionType不能直接在模板中使用.要么将其设置为组件的属性,要么添加要检查的指定方法:

@Component({
    selector: 'test',
    template: `
      <ul class="nav navbar-nav">
        <li class="{{isPrimarySection(activeSection) ? 'active': ''}}"><a href="javscript:void(0);" (click)="setActiveSection(SectionType.Primary)">Primary Details</a></li>
        (...)
      </ul>
    `
  })
  export class TestComponent{
    activeSection: SectionType = SectionType.Primary;
    setActiveSection(section: SectionType) {
      this.activeSection = section;
    }
    isPrimarySection(activeSection) {
      return activeSection == SectionType.Primary
    }
 }
Run Code Online (Sandbox Code Playgroud)

要么

@Component({
    selector: 'test',
    template: `
      <ul class="nav navbar-nav">
      <li class="{{activeSection == SectionType.Primary ? 'active': ''}}"><a href="javscript:void(0);" (click)="setActiveSection(SectionType.Primary)">Primary Details</a></li>
      (...)
    </ul>`
  })
  export class TestComponent{
    activeSection: SectionType = SectionType.Primary;
    setActiveSection(section: SectionType) {
      this.activeSection = section;
    }
    SectionType:SectionType = SectionType;
  }
Run Code Online (Sandbox Code Playgroud)

  • 试试这个:`SectionType = SectionType;` (3认同)
  • 我使用`SectionType:any = SectionType;`.请参阅此plunkr:http://plnkr.co/edit/Mos2zocjWxiYx5rnY4PI?p = preview. (3认同)
  • `SectionType: typeof SectionType = SectionType;` 也有效。 (2认同)