Angular 6 Reactive Forms : How to set focus on first invalid input

前端 未结 6 1336
闹比i
闹比i 2020-12-16 18:21

Under my Angular 6 app , i\'m using Reactive Forms .

My purpose is when submitting , i want to set focus on first invalid input when

6条回答
  •  萌比男神i
    2020-12-16 18:38

    Try this:

    import { Directive, HostListener, ElementRef} from '@angular/core';
    
    @Directive({
      selector: '[focusFirstInvalidField]'
    })
    export class FocusFirstInvalidFieldDirective {
    
      constructor(private el: ElementRef) { }
    
      @HostListener('submit')
      onFormSubmit() {
        const invalidElements = this.el.nativeElement.querySelectorAll('.ng-invalid');
        if (invalidElements.length > 0) {
          console.log(invalidElements[0]); 
    
          invalidElements[0].focus();
        }
      }
    }
    

    Remember to debug, see if element 0 is not your own form as it happened to me, so see right what field it is reporting as the first and put the position right.

提交回复
热议问题