在angular2视图模板中传递枚举

编程入门 行业动态 更新时间:2024-10-21 19:41:18
本文介绍了在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视图模板中传递枚举

本文发布于:2023-11-15 10:29:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1593625.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:视图   模板

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!