Home > Enterprise >  Angular formGroup, scroll to first Invalid input in a scrolling div
Angular formGroup, scroll to first Invalid input in a scrolling div

Time:03-17

I have a significantly large form and the way the application is laid out, the form is in a scrolling div, so I can't use (because it doesn't seem to work) something like:

private scrollToFirstInvalidControl() {
        const firstInvalidControl: HTMLElement = this.el.nativeElement.querySelector(
            "form .ng-invalid"
        );

        firstInvalidControl.focus();
    }

This is a one-off thing, I also don't want it as a directive, it's just overkill, I just want to focus on the first invalid object in the formGroup after I run this.form.markAllAsTouched(); and walk away.. smooth scrolling would be a nice bonus, but not a huge deal.

CodePudding user response:

You can try like this (change formId to actual id of your form:

private scrollToFirstInvalidControl() {
    let form = document.getElementById('formId'); // <-- your formID
    let firstInvalidControl = form.getElementsByClassName('ng-invalid')[0];
    firstInvalidControl.scrollIntoView();
    (firstInvalidControl as HTMLElement).focus();
}
  • Related