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

时间:2016-05-17 13:25:42

标签: 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;
    }
}

这是我的枚举:

enum SectionType {
    Primary,
    Aditional,
    Payment
}

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

2 个答案:

答案 0 :(得分:18)

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

@Component(...)
export class MyComp {
  public MyEnum: any = MyEnum;
}

然后在模板中:

<select>
  <option value="MyEnum.ValueA">Value A</option>
</select>

答案 1 :(得分:12)

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
    }
 }

@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;
  }