我试图在angularjs 2模板中使用enum.

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

推荐答案

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

@Component({
    select或: '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>
    `
  })
  exp或t class TestComponent{
    activeSection: SectionType = SectionType.Primary;
    setActiveSection(section: SectionType) {
      this.activeSection = section;
    }
    isPrimarySection(activeSection) {
      return activeSection == SectionType.Primary
    }
 }

@Component({
    select或: '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>`
  })
  exp或t class TestComponent{
    activeSection: SectionType = SectionType.Primary;
    setActiveSection(section: SectionType) {
      this.activeSection = section;
    }
    SectionType:SectionType = SectionType;
  }

Angular相关问答推荐

iOS Mobile Safari - HTML5视频覆盖一切

Angular 17上的material 工具提示的自定义样式

为什么当我在父组件中设置数组元素时,Angular重新创建子组件而不是更新它?

首期日历发行

确保我的角库S服务构建提供独立的友好提供功能

使用jsPDF生成带有图像的PDF时出现灰色条纹

当快速拖动光标时会丢失元素 - Angular

如何将 Firebase 云消息传递 (FCM) 与 Angular 15 结合使用?

如果observableA在1秒前触发,则过滤掉observableB

Angular APP_INITIALIZER 中的 MSAL 身份验证

清除Angular2中的输入文本字段

如何在两个模块之间共享服务 - @NgModule 在Angular 而不是在组件之间?

angular2:错误: TypeError: Cannot read property '...' of undefined

Angular-CLI 代理到后端不起作用

Angular 2 - ngfor 没有包装在容器中

如何在 Angular 2 中创建可重用的动画

Angular 2 Material 2 日期 Select 器日期格式

Angular 2 filter/search 列表

如何在项目中导入 Angular material?

declarations和entryComponents组件有什么区别