在angular2视图模板中传递枚举 [英] Pass enums in angular2 view templates

查看:165
本文介绍了在angular2视图模板中传递枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以在angular2视图模板中使用枚举吗?

Can we use enums in an angular2 view template?

<div class="Dropdown" dropdownType="instrument"></div>

将字符串作为输入传递:

passes the string as input:

enum DropdownType {
    instrument,
    account,
    currency
}

@Component({
    selector: '[.Dropdown]',
})
export class Dropdown {

    @Input() public set dropdownType(value: any) {

        console.log(value);
    };
}

但是如何通过枚举配置呢?我想要在模板中添加以下内容:

But how to pass an enum configuration? I want something like this in the template:

<div class="Dropdown" dropdownType="DropdownType.instrument"></div>

最佳做法是什么?

创建了一个示例:

import {bootstrap} from 'angular2/platform/browser';
import {Component, View, Input} from 'angular2/core';

export enum DropdownType {

    instrument = 0,
    account = 1,
    currency = 2
}

@Component({selector: '[.Dropdown]',})
@View({template: ''})
export class Dropdown {

    public dropdownTypes = DropdownType;

    @Input() public set dropdownType(value: any) {console.log(`-- dropdownType: ${value}`);};
    constructor() {console.log('-- Dropdown ready --');}
}

@Component({ selector: 'header' })
@View({ template: '<div class="Dropdown" dropdownType="dropdownTypes.instrument"> </div>', directives: [Dropdown] })
class Header {}

@Component({ selector: 'my-app' })
@View({ template: '<header></header>', directives: [Header] })
class Tester {}

bootstrap(Tester);

推荐答案

在父组件上为您的枚举创建属性,并将其分配给组件类,然后在模板中引用该属性.

Create a property for your enum on the parent component to your component class and assign the enum to it, then reference that property in your template.

export class Parent {
    public dropdownTypes = DropdownType;        
}

export class Dropdown {       
    @Input() public set dropdownType(value: any) {
        console.log(value);
    };
}

这使您可以按预期在模板中枚举枚举.

This allows you to enumerate the enum as expected in your template.

<div class="Dropdown" [dropdownType]="dropdownTypes.instrument"></div>

这篇关于在angular2视图模板中传递枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆