Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Focus on first invalid input after Click/Event

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!

like image 374
Jared Martinez Avatar asked Dec 15 '16 20:12

Jared Martinez


1 Answers

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.

scrollTo(el: Element): void {
   if(el) { 
    el.scrollIntoView({ behavior: 'smooth' });
   }
}

scrollToError(): void {
   const firstElementWithError = document.querySelector('.ng-invalid');
   this.scrollTo(firstElementWithError);
}

async scrollIfFormHasErrors(form: FormGroup): Promise <any> {
  await form.invalid;
  this.scrollToError();
}

This works, allowing you to evade manipulating the DOM. It simply goes to the first element with .ng-invalid on the page through the document.querySelector() which returns the first element in the returned list.

To use it:

this.scrollIfFormHasErrors(this.form).then(() => {
  // Run any additional functionality if you need to. 
});

I also posted this on Angular's Github page: https://github.com/angular/angular/issues/13158#issuecomment-432275834

like image 140
jburtondev Avatar answered Sep 20 '22 06:09

jburtondev