Search code examples
angulartypescriptangular-componentsangular-forms

Angular form, how to scroll to top automatically after successful submission of form?


I could not find a workable solution for my angular form. Basically I wish to scroll back to the top automatically after my form is being captured successfully.

I am able to capture the submission and reset the form but is having some difficulty in trying to scroll back to the top automatically after form reset.

This is my onSubmit() function in my account-payable.component.ts:

onSubmit() {
    this.submitted = true;

    // stop here if form is invalid
    if (this.accountPayableForm.invalid) {
      return;
    }

    this.loading = true;
    this.accountPayableService
      .submitAccountPayable(this.accountPayableForm.value)
      .pipe(first())
      .subscribe(
        data => {
          this.alertService.success(
            'Success! Account payable created with reference ID: ' +
              data.valueOf(),
            true
          );
          this.loading = false;
          this.submitted = false;
          this.accountPayableForm.reset();
          this.goToTop();
        },
        error => {
          this.alertService.error(error);
          this.loading = false;
        }
      );
  }

My goToTop() function doesn't seems to be working:

goToTop() {
    window.scroll({
      top: 0,
      left: 0,
      behavior: 'smooth'
    });
  }

I have tried to replace this.goToTop(); with window.scrollTo(0,0); but it's not working as well, my form still stays at the bottom and my success message is displayed above the form and I'll have to manually scroll up to check after submission.

Any advise? Thanks.


Solution

  • try:

    document.querySelector("main").scrollTo(0, 0);
    

    Where you replace "main" with whatever element that you have wrapped around <router-outlet>.

    You couldn't use window because it's likely you have nested your <router-outlet> inside another element. In my program for example, I have wrapped a <main> element around <router-outlet>:

    enter image description here

    hence, I have to select <main> element and target it to scroll to top.

    I don't know how your app is structured and I think it is a waste of time to ask you to post the structure of app. Examine your dev tools' Elements tab (Chrome) or Inspector tab (firefox) and target the correct element that has a defined height (which allowed scrolling to happen; Note: it may not even be an element that wraps around router-outlet!). You should be able to scroll to top then.

    You can actually test document.querySelector("main").scrollTo(0, 0); in the browser's console to see if you're targetting the correct element and the scroll is working (ignore the undefined response):

    enter image description here