2017-02-26 81 views
7

我想使用一個枚舉值來設置HTML屬性的設定值:Angular2使用枚舉值

export enum MyEnum { 
    FirstValue, 
    SecondValue 
} 
export function MyEnumAware(constructor: Function) { 
    constructor.prototype.MyEnum = MyEnum; 
} 

@MyEnumAware 
@Component({ 
    templateUrl: "./lot-edit.component.html", 
    styleUrls: ["./lot-edit.component.css"], 
}) 
export class LotEditComponent implements OnInit { 
    @Input() myEnumValue: MyEnum ; 

}

<td><input name="status" type="radio" [value]="MyEnum.FirstValue" [(ngModel)]="myEnumValue"></td> 
<td><input name="status" type="radio" [value]="MyEnum.SecondValue" [(ngModel)]="myEnumValue"></td> 

但是我得到「無法讀取屬性'FirstValue'未定義「

有沒有辦法使用枚舉值作爲html屬性的值?

+0

https://stackoverflow.com/questions/45799745/pass-enum-value-to-angular-2-component/45800962#45800962 –

回答

12

您的模板只能訪問其組件類的成員變量。所以,如果你想使用枚舉的值,把它(Enum)賦值給一個成員變量。

在您的組件,

export class MyComp { 
    MyEnum = MyEnum; 
    ..... 
} 

然後你可以自由地訪問枚舉的元素在你的模板。

+0

這是一個正確的做法嗎?我不會這麼說。 –

+0

但是,爲什麼不呢? – snorkpete

+0

我經常使用這種技術的變體,我有一個對象,其屬性是我認爲是常量的字符串,我會根據需要將該對象附加到各種組件。最常見的例子是爲我想在該對象字面量中使用的材質設計圖標定義項目特定名稱,然後在需要它的地方使用該對象字面量 – snorkpete

2

可以使用一個枚舉由於使用分配給html元素如下

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <h2>Hello {{name}}</h2> 
     <input type="text" [(ngModel)]="value"/> 
    </div> 
    `, 
}) 
export class App { 
    name:string; 
    myValue:any= MyEnum; 
    value:string; 
    constructor() { 
    this.name = 'Angular2'; 
    this.value=this.myValue[1]; 
    console.log(this.value); 
    } 
} 

[(ngModel)]輸入元件上,則不能分配給輸入單元的[value]屬性。

LIVE DEMO

-1

具有角2 //枚舉

export enum IType 
{ 
    Vegetables = 0, 
    Fruits = 1, 
    Fish = 2 
} 

//角2組件式腳本

import {IType} from '/itype'; 
export class DataComponent 
{ 
getType(id:number):any 
{ 
     return IType[id]; 
} 
} 

//在HTML文件中

<div> 
{{getType(1)}} 
</div> 
+0

我不確定這個問題的答案。你沒有在html中使用枚舉,你正在使用一個函數來獲取枚舉值。恕我直言,它擊敗了枚舉的使用,因爲現在我在html模板中有一個幻數,我完全不知道它來自哪裏。 –