Angular 2 Focus on first invalid input after Click/Event

前端 未结 9 1736
不思量自难忘°
不思量自难忘° 2021-02-04 03:46

I have an odd requirement and was hoping for some help.

I need to focus on the first found invalid input of a form after clicking a button (not submit). The form is rath

9条回答
  •  终归单人心
    2021-02-04 04:38

    I don't know if this is valid approach or not but this is working great for me.

    import { Directive, Input, HostListener, ElementRef } from '@angular/core';
    import { NgForm } from '@angular/forms';
    import * as $ from 'jquery';
    
    @Directive({ selector: '[accessible-form]' })
    export class AccessibleForm {
    
        @Input('form') form: NgForm;
    
        constructor(private el: ElementRef) {
    
        }
    
        @HostListener('submit', ['$event'])
        onSubmit(event) {
            event.preventDefault();
    
            if (!this.form.valid) {
                let target;
    
                target = this.el.nativeElement.querySelector('.ng-invalid')
    
                if (target) {
                    $('html,body').animate({ scrollTop: $(target).offset().top }, 'slow');
                    target.focus();
                }
            }
        }
    
    }
    

    In HTML

    I have mixed the approach of angularjs accessible form directive in this. Improvements are welcomed!!!

提交回复
热议问题