将枚举值传递给角度2分量 [英] Pass enum value to angular 2 component
问题描述
我有一个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.
这篇关于将枚举值传递给角度2分量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!