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

前端 未结 6 1347
闹比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条回答
  •  无人及你
    2020-12-16 18:51

    This option does not work for me, but I managed to fix it by changing the code as follows:

    @Directive({
      selector: '[appErrorFocusin]'
    })
    export class ErrorFocusinDirective {
    
      selectorToFocus : String = 'textArea,mat-select,select,input,button';
    
      constructor(private el: ElementRef,
        @Inject(DOCUMENT) private document: Document) { }
    
      @Input() formGroup: NgForm;
    
      @HostListener('submit', ['$event'])
      public onSubmit(event): void {
        if ('INVALID' === this.formGroup.status) {
          event.preventDefault();
    
          const formGroupInvalid = this.el.nativeElement.querySelectorAll('.ng-    invalid,:not(.mat-badge-hidden).mat-badge');
          let elementToOffset = this.getElementToOffset(formGroupInvalid[0]);
          this.document.documentElement.scrollTop = elementToOffset.offsetTop;
          this.setFocusOnError(elementToOffset);
        }
      }
    
    
      getElementToOffset(element : any){
        let defaultElement = element;
        while (!(element.parentElement instanceof HTMLFormElement)){
          if (element.parentElement){
            element = element.parentElement;
          }else{
            return defaultElement;
          }
        }
        return element;
      }
    
      setFocusOnError(elementToOffset : any){
        let listaElementos =     elementToOffset.querySelectorAll(this.selectorToFocus);
        if (listaElementos.length>0){
          listaElementos[0].focus();
        }
      }
    
    }
    

提交回复
热议问题