Angular 2 Focus on first invalid input after Click/Event

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

    If you are using AngularMaterial, the MdInputDirective has a focus() method which allow you to directly focus on the input field.

    In your component, just get a reference to all the inputs with the @ViewChildren annotation, like this:

    @ViewChildren(MdInputDirective) inputs: QueryList;

    Then, setting focus on the first invalid input is as simple as this:

    this.inputs.find(input => !input._ngControl.valid).focus()

提交回复
热议问题