Angular 2 Focus on first invalid input after Click/Event

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

    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.

提交回复
热议问题