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!
I recommend putting this in a service, for me it worked like this:
This works for me. Not the most elegant solution, but given the constraints in Angular we are all experiencing for this particular task, it does the job.
This works, allowing you to evade manipulating the DOM. It simply goes to the first element with
.ng-invalid
on the page through thedocument.querySelector()
which returns the first element in the returned list.To use it:
I also posted this on Angular's Github page: https://github.com/angular/angular/issues/13158#issuecomment-432275834
I don't know if this is valid approach or not but this is working great for me.
In HTML
I have mixed the approach of angularjs accessible form directive in this. Improvements are welcomed!!!
I've created an Angular directive to solve this problem. You can check it here ngx-scroll-to-first-invalid.
Steps:
1.Install the module:
2.Import the
NgxScrollToFirstInvalidModule
:3.Use the directive inside a form:
Hope it helps! :)
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<MdInputDirective>;
Then, setting focus on the first invalid input is as simple as this:
this.inputs.find(input => !input._ngControl.valid).focus()