How to get name of input field from Angular2 FormControl object?
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;}
We can use .parent
property, well today ["_parent"]
(see more below):
export const getControlName = (control: ng.forms.AbstractControl) =>{ var controlName = null; var parent = control["_parent"]; // only such parent, which is FormGroup, has a dictionary // with control-names as a key and a form-control as a value if (parent instanceof ng.forms.FormGroup) { // now we will iterate those keys (i.e. names of controls) Object.keys(parent.controls).forEach((name) => { // and compare the passed control and // a child control of a parent - with provided name (we iterate them all) if (control === parent.controls[name]) { // both are same: control passed to Validator // and this child - are the same references controlName = name; } }); } // we either found a name or simply return null return controlName;}
and now we are ready to adjust our validator definition
public asyncValidator(control: FormControl): {[key: string]: any} { //var theFieldName = control.someMethodOfGettingTheName(); // this is the missing piece var theFieldName = getControlName(control); ...
.parent
later, ["_parent"]
now
At the moment (today, now), current release is :
But following this issue: feat(forms): make 'parent' a public property of 'AbstractControl'
And as already stated here
Features
- forms: make 'parent' a public property of 'AbstractControl' (#11855) (445e592)
- ...
we could later change the ["_parent"]
into .parent
As of Angular 4.2.x, you can access a FormControl
's parent FormGroup
(and its controls) using the public parent property:
private formControl: FormControl;//...Object.keys(this.formControl.parent.controls).forEach((key: string) => { // ...});