2016-05-17 115 views
14

我想在angularjs 2模板中使用enum。 下面是我的代碼如何在Angular 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 
} 

它引發異常:類型錯誤:無法讀取未定義

回答

9

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

第一解決方案可能工作,但怎麼樣'(點擊)=「setActiveSection(SectionType.Primary)」' 和第二個解決方案 'SectionType:SectionType = SectionType;'給出錯誤 Type'Typeof SectionType'不可分配給'SectionType' –

+3

試試這個:'SectionType = SectionType;' –

+2

我使用'SectionType:any = SectionType;'。看到這個plunkr:http://plnkr.co/edit/Mos2zocjWxiYx5rnY4PI?p=preview。 –

3

在模板中使用枚舉簡單的方法是

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

然後在模板中:

<select> 
    <option value="MyEnum.ValueA">Value A</option> 
</select> 
相關問題