How can I get the full path of FormControl in angular 4+?
I have the reactive form:
{
name: '',
address: {
city: '',
country: ''
}
}
And I rly need to get full path of control:
const addressFormGroup = this.form.get('address');
const cityControl = addressFormGroup.get('city');
cityControl.plsGiveMeFullPath() //address.city
Is there existing method to get the full path of cityControl: FormControl | FormGroup?
I implemented these two methods to get this functionality.
The first one is a helper that returns the name of a control (as it is indexed in its parent). The function achieves that by searching on its parent's controls
object the control that equals the one that you gave it, and then returning the key.
The second one is a recursive function that calls returns the name of the control using the helper above and calls itself for the control's parent, joining the return string with dots ('.').
getControlName(c: AbstractControl): string | null {
if(!c.parent) return null;
const formGroup = c.parent.controls;
return Object.keys(formGroup).find(name => c === formGroup[name]) || null;
}
getControlPath(c: AbstractControl, path: string): string | null {
path = this.getControlName(c) + path;
if(c.parent && this.getControlName(c.parent)) {
path = "."+path;
return this.getControlPath(c.parent, path);
} else {
return path;
}
}
@lonix Too long for a comment...
formGroup
is either AbstractControl[]
or { [key: string]: AbstractControl }
, so just test for array and everything works as expected:
export const getControlName = (control: AbstractControl): string | null => {
if (control.parent == null) {
return null;
}
const children = control.parent.controls;
if (Array.isArray(children)) {
for (let index = 0; index < children.length; index++) {
if (children[index] === control) {
return `${index}`;
}
}
return null;
}
return Object.keys(children).find(name => control === children[name]) || null;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With