如何从Angular2 FormControl对象获取输入字段的名称? [英] How to get name of input field from Angular2 FormControl object?

查看:253
本文介绍了如何从Angular2 FormControl对象获取输入字段的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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);
          });
    });
  }

推荐答案

扩展RadimKö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对象获取输入字段的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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