I am using ngx-formly for creating dynamic form from field configuration. On submitting form, validation is showed correctly. I want to focus first invalid formly field.
1 Answer
A little late to the party here but I was able to implement a solution that returned the user to the first instance of an invalid input using getElementById:
var errorField = null;
fields.forEach(field => {
for (var key in field.formControl["controls"]) {
let control = field.formControl["controls"][key];
if (control instanceof FormControl && control.status === "INVALID") {
errorField = control["_fields"][0]["_elementRefs"][0].nativeElement.id;
break;
}
else if (control instanceof FormGroup) {
for (var subKey in control.controls) {
let subControl = control.controls[subKey];
if (subControl.status === "INVALID") {
errorField = subControl["_fields"][0]["_elementRefs"][0].nativeElement.id;
break;
}
}
}
if (errorField) break;
}
});
let el = document.getElementById(errorField);
el.scrollIntoView({
behavior: 'smooth',
block: "center"
});