My Angular 2 application features the ReactiveForms
module for managing a form with its own custom validator. This validator takes in a FormControl
object as an input parameter. I've noticed that multiple input fields could benefit from using this same custom validator if only there was a way to determine the field's name when passing the FormControl
to the validator.
I've searched extensively but haven't been able to find any method or public property within the FormControl
that exposes the name of the input field. While it's easy to access the value, retrieving the field's name seems to be the missing piece of the puzzle. The code snippet below demonstrates how I envision utilizing this functionality:
public asyncValidator(control: FormControl): {[key: string]: any} {
var theFieldName = control.someMethodOfGettingTheName(); // this is where I need help
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);
});
});
}