Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 form validation Error Scroll

I want to implement the reactive form validations in angular 2.When user clicks on submit button the page will scroll up to the required error.

@ViewChild('focuserror') errorElement: ElementRef;
      ngAfterViewInit() {
        this.renderer.invokeElementMethod(this.errorElement.nativeElement.querySelector('.ng-invalid'), 'focus');
       }

Is this the right code? It's throwing error

  • typeError: Cannot read property 'focus' of null
like image 637
Diggi Avatar asked Mar 26 '18 11:03

Diggi


1 Answers

you can do this:

formSubmitFunction() {

  const firstElementWithError = document.querySelector('.ng-invalid');

  if (firstElementWithError) {
    firstElementWithError.scrollIntoView({ behavior: 'smooth' });
  }
}

you can use any class you have used in form validation.

like image 111
anurag619 Avatar answered Jan 04 '23 10:01

anurag619