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

前端 未结 6 1348
闹比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:46

    I did that using directives. So My form would look like this:

    ...

    and the code for the directive itself:

    import { Directive, HostListener, Input, ElementRef } from '@angular/core';
    import { NgForm } from '@angular/forms';
    
    @Directive({
      selector: '[appFocus]'
    })
    export class FocusDirective {
    
      constructor(private el: ElementRef) { }
    
      @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');
          (formGroupInvalid[0]).focus();
        }
      }
    }
    

    However this solution is incomplete as there is a lot of corner cases that have to be considered. For example what if the first element is radio button group. Dispatching focus event will automatically mark the filed. Second not every element to which angular ads ng-invalid will be an input.

提交回复
热议问题