Angular 2 Focus on first invalid input after Click/Event

前端 未结 9 1705
不思量自难忘°
不思量自难忘° 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:46

    I recommend putting this in a service, for me it worked like this:

    if (this.form.valid) {
      //submit
    } else {
      let control;
      Object.keys(this.form.controls).reverse().forEach( (field) => {
        if (this.form.get(field).invalid) {
          control = this.form.get(field);
          control.markAsDirty();
        }
      });
    
      if(control) {
        let el = $('.ng-invalid:not(form):first');
        $('html,body').animate({scrollTop: (el.offset().top - 20)}, 'slow', () => {
          el.focus();
        });
      }
    }
    

提交回复
热议问题