Skip to content
Advertisement

Angular: Scroll and focus to first invalid control in nested form once form has been submitted

I am trying to scroll and focus invalid control in form onsubmit. If I am using single form element its working as expected but when I am using nested form element not working.

please find the sample example here stackblitz.

How to scroll to invalid control and focus in nested forms on submit rootform.

Advertisement

Answer

I think I’ve found a solution to your problem.

In your directive, inside the method scrollToFirstInvalidControl change the line:

const firstInvalidControl: any = this.el.nativeElement.querySelector('.ng-invalid');

with:

let firstInvalidControl: any;
    let all = document.getElementsByClassName('ng-invalid');
    for (var i = 0; i < all.length; i++) {
      if(all[i].tagName == 'INPUT'){
        firstInvalidControl = all[i];
        break;
    }
}

It will take all elements that have a ng-invalid class, but will check only those that have a tagName as INPUT – since your validation is for input fields, not whole forms as such (your original code caught first invalid form, but that wasn’t the form that had an input that you wanted to scroll to).

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement