本文介绍了在 angular2 视图模板中传递枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们可以在 angular2 视图模板中使用枚举吗?
</div>将字符串作为输入传递:
enum DropdownType {仪器,帐户,货币}@成分({选择器: '[.Dropdown]',})导出类下拉{@Input() public set dropdownType(value: any) {控制台日志(值);};}
但是如何传递一个枚举配置呢?我想在模板中这样的东西:
</div>最佳做法是什么?
创建了一个示例:
import {bootstrap} from 'angular2/platform/browser';从'angular2/core'导入{组件、视图、输入};导出枚举 DropdownType {仪器 = 0,帐户 = 1,货币 = 2}@Component({选择器: '[.Dropdown]',})@View({模板:''})导出类下拉{公共 dropdownTypes = DropdownType;@Input() public set dropdownType(value: any) {console.log(`-- dropdownType: ${value}`);};构造函数(){console.log('--下拉准备好--');}}@Component({ 选择器: 'header' })@View({ 模板:'<div class="Dropdown" dropdownType="dropdownTypes.instrument"> </div>', 指令:[Dropdown] })类标题{}@Component({ 选择器: 'my-app' })@View({ 模板: '</header>', 指令: [Header] })类测试员{}引导程序(测试员);
解决方案 为组件类的父组件上的枚举创建一个属性并将枚举分配给它,然后在模板中引用该属性.
export class Parent {public dropdownTypes = DropdownType;}导出类下拉{@Input() public set dropdownType(value: any) {控制台日志(值);};}
这允许您在模板中按预期枚举枚举.
<div class="Dropdown" [dropdownType]="dropdownTypes.instrument"></div>
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>
What would be the best practice?
Edited:Created an example:
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 视图模板中传递枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-02 01:52