How to use enum in Angular 2 templates

后端 未结 2 991
我在风中等你
我在风中等你 2021-02-05 00:37

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

@Component({
    selector: \'test\',
    template: `
    &
相关标签:
2条回答
  • 2021-02-05 00:55

    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>
    
    0 讨论(0)
  • 2021-02-05 01:07

    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;
      }
    
    0 讨论(0)
提交回复
热议问题