如何在角度2中使用自定义枚举属性

时间:2017-04-22 00:36:07

标签: angular enums properties

我是角色2的新手,虽然使用它来构建应用程序。我来自CSharp背景,因此假设可以创建枚举类型属性。以便根据其位置应用特定的枚举值。

但是我没有在网上找到解释如何实现这种技术的例子。是否有可能,如果可以的话,你能提供演示吗?

export enum DisplayType {
  Small,
  Large
}

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

如果不可能,是否有其他技术可以达到相同的效果。

4 个答案:

答案 0 :(得分:0)

你不能在HTML中处理这样的变量名,而应该使用一种方法来获取枚举值

var s = "string s1 = \"foo\"; string s2 = \"bar\"; string s3 = \"baz\";";

var list = new List<string>();

var result = Regex.Replace(s, "\".*?\"", m => { list.Add(m.Value); 
                                                return "#" + (list.Count - 1) + "#"; });

注意:在您的问题中,displayType没有<e-view [displayType]="getType()"></e-view> getType(){ return DisplayType.Small }

答案 1 :(得分: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;
  }
}

答案 2 :(得分:0)

在您的组件中,再添加一个getter

get DisplayType() {
  return DisplayType;
}

您可以在模板中使用

[displayType]="DisplayType.Small"

答案 3 :(得分:0)

在使用枚举的组件中,添加一个属性:

readonly DisplayType: typeof DisplayType = DisplayType;

然后用HTML调用枚举:

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