Angular 2 Focus on first invalid input after Click

2020-05-23 02:44发布

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 rather large, and so the screen needs to scroll to the first invalid input.

This AngularJS answer would be what I would need, but didn't know if a directive like this would be the way to go in Angular 2:

Set focus on first invalid input in AngularJs form

What would be the Angular 2 way to do this? Thanks for all the help!

9条回答
叼着烟拽天下
2楼-- · 2020-05-23 03:14

Plain HTML solution. If you don't need to be scrolling , just focus on first valid input, I use :

public submitForm() {
    if(this.form.valid){
        // submit form
    } else {
        let invalidFields = [].slice.call(document.getElementsByClassName('ng-invalid'));
        invalidFields[1].focus();
    }
}

This is for template driven form here. We focus on second element of invalidFields cuz first is the whole form which is invalid too.

查看更多
Root(大扎)
3楼-- · 2020-05-23 03:14

For Angular Material , The below worked for me

@ViewChildren(MatInput) inputs: QueryList <MatInput>;
this.inputs.find(input => !input.ngControl.valid).focus();
查看更多
对你真心纯属浪费
4楼-- · 2020-05-23 03:15

Unfortunately I can't test this at the moment, so might be a few bugs, but should be mostly there. Just add it to your form.

import {Directive, Input, HostListener} from '@angular/core';
import {NgForm} from '@angular/forms';

@Directive({ selector: '[scrollToFirstInvalid]' })
export class ScrollToFirstInvalidDirective {
  @Input('scrollToFirstInvalid') form: NgForm;
  constructor() {
  }
  @HostListener('submit', ['$event'])
  onSubmit(event) {
    if(!this.form.valid) {
      let target;
      for (var i in this.form.controls) {
        if(!this.form.controls[i].valid) {
          target = this.form.controls[i];
          break;
        }
      }
      if(target) {
        $('html,body').animate({scrollTop: $(target.nativeElement).offset().top}, 'slow');
      }
    }
  }
}
查看更多
登录 后发表回答