Как использовать перечисление в Angular 2 шаблонах

Я пытаюсь использовать перечисление в шаблонах 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" из undefined

Ответы

Ответ 1

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

Ответ 2

Простой способ использовать Enum в шаблоне

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

Тогда в шаблоне:

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