Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 522
kaiilim Avatar asked Sep 07 '25 15:09

kaiilim


1 Answers

If you just want to scroll to top, use this:

window.scrollTo(0,0);
like image 65
maryrio7 Avatar answered Sep 09 '25 05:09

maryrio7