gpt4 book ai didi

angular - 如何从 Angular2 FormControl 对象获取输入字段的名称?

转载 作者:太空狗 更新时间:2023-10-29 16:51:27 26 4
gpt4 key购买 nike

我有一个 Angular 2 应用程序,它使用 ReactiveForms 模块来管理使用自定义验证器的表单。验证器接收一个 FormControl 对象。我有几个输入字段可以使用相同的自定义验证器,只要我在 FormControl 传递给验证器时知道字段的名称即可。

我在 FormControl 上找不到任何公开输入字段名称的方法或公共(public)属性。当然,很容易看出它的值(value)。下面显示了我想如何使用它:

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 的回答。这是编写该函数的一种较短的方法。

getControlName(c: AbstractControl): string | null {
const formGroup = c.parent.controls;
return Object.keys(formGroup).find(name => c === formGroup[name]) || null;
}

关于angular - 如何从 Angular2 FormControl 对象获取输入字段的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40361799/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com