问题描述
我有一个 Angular 2 应用程序,它使用 ReactiveForms
模块来管理使用自定义验证器的表单.验证器接收一个 FormControl
对象.我有几个输入字段可以使用相同的自定义验证器,前提是我在将 FormControl
传递给验证器时知道该字段的名称.
I have an Angular 2 application that uses the ReactiveForms
module to manage a form that uses a custom validator. The validator receives a FormControl
object. I have a few input fields that could use the same custom validator if only I knew the name of the field when the FormControl
was passed to the validator.
我在 FormControl
上找不到任何公开输入字段名称的方法或公共属性.当然,很简单就能看出它的价值.下面显示了我想如何使用它:
I can't find any method or public property on FormControl
that exposes the input field's name. It's simple enough to see its value, of course. The following shows how I would like to use it:
public asyncValidator(control: FormControl): {[key: string]: any} {
var theFieldName = control.someMethodOfGettingTheName(); // this is the missing piece
return new Promise(resolve => {
this.myService.getValidation(theFieldName, control.value)
.subscribe(
data => {
console.log('Validation success:', data);
resolve(null);
},
err => {
console.log('Validation failure:', err);
resolve(err._body);
});
});
}
推荐答案
扩展 Radim Köhler 的答案.这是编写该函数的一种更简短的方法.
To expand on Radim Köhler answer. here is a shorter way of writing that function.
getControlName(c: AbstractControl): string | null {
const formGroup = c.parent.controls;
return Object.keys(formGroup).find(name => c === formGroup[name]) || null;
}
这篇关于如何从 Angular2 FormControl 对象获取输入字段的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!