2017-04-22 103 views
0

我是angular 2的新手,儘管使用它來構建應用程序。我來自CSharp背景,因此假定可以創建枚舉類型屬性。以便根據其位置應用特定的枚舉值。如何在角度2中使用自定義枚舉屬性

但是我找不到在線的例子來解釋如何實現這種技術。有沒有可能,如果可以的話,你可以提供演示嗎?

export enum DisplayType { 
    Small, 
    Large 
} 

<e-view displayType="DisplayType.Small"></e-view> 

如果不可能,還有其他技術可以達到相同的結果。

回答

0

你不能處理的變量名像這樣的HTML,而不是你應該使用的方法來獲取枚舉值

<e-view [displayType]="getType()"></e-view> 
getType(){ 
    return DisplayType.Small 
} 

注意:你的問題顯示類型沒有[ ]

+0

所以枚舉不能用於這樣的目的,好吧...然而,我想指定顯示類型在視圖組件中,如下所示: 。如果displayType是字符串類型,我怎麼能應用它在HTML模板? – vicgoyso

+0

你將如何定義一個枚舉有字符串 – Aravind

+0

不,現在考慮只是現在使用一個字符串,因爲不能使用枚舉。我想知道如何將值「小」傳遞給我的html模板? – vicgoyso

0
export enum AgentStatus { 
    available =1 , 
    busy = 2, 
    away = 3, 
    offline = 0 
} 

如何將字符串轉換爲TypeScript中的枚舉?

var value = AgentStatus["offline"]; // so value is now 0 

// You can also use this, which only gives IDE hints, no runtime benefit 
var value: AgentStatus = AgentStatus["offline"]; 

如何獲取TypeScript枚舉類型的所有值?

var options : string[] = Object.keys(AgentStatus); 
// The options list has the numeric keys, followed by the string keys 
// So, the first half is numeric, the 2nd half is strings 
options = options.slice(options.length/2); 

如果您在Angular2模板寫:

{{AgentStatus[myValue]}} 

它會失敗,因爲它並沒有獲得進口類型(它被用AngularJS後執行)。

要使其工作,你的組件需要有枚舉類型/對象的引用,是這樣的:

export class MyComponent { 
    // allows you to use AgentStatus in template 
    AgentStatus = AgentStatus;   

    myValue : AgentStatus; 
    // ... 
} 

例如:

import { Component } from '@angular/core'; 

enum AgentStatus { 
    available =1 , 
    busy = 2, 
    away = 3, 
    offline = 0 
} 

例如

@Component({ 
    selector: 'my-app', 
    template: ` 
    <h1>Choose Value</h1> 

    <select (change)="parseValue($event.target.value)"> 
    <option>--select--</option> 
    <option *ngFor="let name of options" 
     [value]="name">{{name}}</option> 
    </select> 

    <h1 [hidden]="myValue == null"> 
    You entered {{AgentStatus[myValue]}} 
    <br> 
    You are {{isOffline ? "offline" : "not offline"}}. 
    </h1>` 
}) 
export class AppComponent { 


    options : string[]; 
    myValue: AgentStatus; 
    AgentStatus : typeof AgentStatus = AgentStatus; 
    isOffline : bool; 

    ngOnInit() { 
    var x = AgentStatus; 
    var options = Object.keys(AgentStatus); 
    this.options = options.slice(options.length/2); 
    } 

    parseValue(value : string) { 
    this.myValue = AgentStatus[value]; 
    this.isOffline = this.myValue == AgentStatus.offline; 
    } 
} 
0

在您的組件中,再添加一個吸氣器

get DisplayType() { 
    return DisplayType; 
} 

,你可以在你的模板

[displayType]="DisplayType.Small" 
0

使用在組件使用的枚舉,添加屬性:

readonly DisplayType: typeof DisplayType = DisplayType; 

然後調用枚舉在HTML:

<e-view [displayType]="DisplayType.Small"></e-view>