如何在Angular 2模板中使用枚举 [英] How to use enum in Angular 2 templates

查看:149
本文介绍了如何在Angular 2模板中使用枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在angularjs 2模板中使用枚举. 下面是我的代码

I am trying to use enum in angularjs 2 templates. Below is my code

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

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

It is throwing EXCEPTION: TypeError: Cannot read property 'Primary' of undefined

推荐答案

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

SectionType can't be used directly within the template. Either you set it to a property of your component, either you add specify methods to check:

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

这篇关于如何在Angular 2模板中使用枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆