简体   繁体   中英

How to use enum in Angular 2 templates

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

here is my enum:

enum SectionType {
    Primary,
    Aditional,
    Payment
}

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

The simple way to use an Enum in a template is

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

Then in template:

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

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM