将枚举值传递给 angular 2 组件 [英] Pass enum value to angular 2 component

查看:27
本文介绍了将枚举值传递给 angular 2 组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 enum,想从模板传递 enum 值.这怎么可能?

I have an enum, and want to pass from template the enum value. How is this possible?

export enum FIELDS {
    GENDER = <any>'Gender',
    SALUTATION = <any>'Salutation',
    FIRSTNAME = <any>'First Name',
    LASTNAME = <any>'Last Name',
    EMAIL_ADDRESS = <any>'Email Address',
    COUNTRY = <any>'Country',

}

我的模板.这里我想传递枚举值

my template. Here i want to pass the enum value

 [ngClass]="{'error':validate(FIELDS.COUNTRY)}" 

//这会引发错误:无法获取未定义或空引用的属性 COUNTRY.

//this throws an error: Unable to get property COUNTRY of undefined or null reference.

我的组件:

@Component({
  selector: 'row-general',
  template: require('./modify-invalid-row-general.component.html'),
  styleUrls: ['./app/nedit/modify-invalid-row/modify-invalid-row.component.css']
})
export class ModifyInvalidRowGeneralComponent {

  @Input() row: UploadRow;
  @Input() columns: ConfigColumn[];

  @Output() validateRow = new EventEmitter<UploadRow>();

  public validate(field: string): boolean {

    let invalidFields: string[] = [];
    if (this.row.invalidFields != null)
      invalidFields = this.row.invalidFields.split(';');
    for (let i = 0; i < invalidFields.length; i++) {
       if (invalidFields[i].trim() == field.trim())
        return true;
    }
    return false;
  }

如果我通常在组件中调用 FIELDS.COUNTRY,我会得到值Country".这就是我需要的.

if I normally call FIELDS.COUNTRY in the component I get the value 'Country'. That's what I need.

有人知道,我如何传递 enum 值?

Anybody know, how can I pass the enum value?

推荐答案

您不能直接从模板访问枚举.或者,您可以将它们复制到您的组件中,然后在您的组件中使用它.

You can't access enums directly form you template. Alternately, you can copy them into your component and then use it in your component.

@Component({
  selector: 'row-general',
  template: require('./modify-invalid-row-general.component.html'),
  styleUrls: ['./app/nedit/modify-invalid-row/modify-invalid-row.component.css']
})
export class ModifyInvalidRowGeneralComponent {

  @Input() row: UploadRow;
  @Input() columns: ConfigColumn[];

  @Output() validateRow = new EventEmitter<UploadRow>();

  FILEDS:any=Object.assign({},FIELDS);

  public validate(field: string): boolean {

    let invalidFields: string[] = [];
    if (this.row.invalidFields != null)
      invalidFields = this.row.invalidFields.split(';');
    for (let i = 0; i < invalidFields.length; i++) {
       if (invalidFields[i].trim() == field.trim())
        return true;
    }
    return false;
  }

我使用过 Object.assign 获取枚举对象并复制它(对它的引用不起作用).现在您在组件中拥有枚举实例,您也可以在模板中自由使用它.

I've used Object.assign to take the enum object and copy it (Reference to it won't work ). Now you have you enum instance in your component and you can use it freely it your template as well.

这篇关于将枚举值传递给 angular 2 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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