首页 > 解决方案 > Angular表单,成功提交表单后如何自动滚动到顶部?

问题描述

我找不到适合我的角度形式的可行解决方案。基本上,我希望在成功捕获表单后自动滚动回顶部。

我能够捕获提交并重置表单,但是在表单重置后尝试自动滚动回顶部时遇到了一些困难。

这是我onSubmit()在我的功能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;
        }
      );
  }

我的goToTop()功能似乎不起作用:

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

我尝试替换this.goToTop();为,window.scrollTo(0,0);但效果不佳,我的表单仍停留在底部,并且我的成功消息显示在表单上方,提交后我必须手动向上滚动以检查。

有什么建议吗?谢谢。

标签: angulartypescriptangular-componentsangular-forms

解决方案


如果您只想滚动到顶部,请使用:

window.scrollTo(0,0);

推荐阅读