【问题标题】:Changing query params - page scrolls top, Angular更改查询参数 - 页面滚动到顶部,Angular
【发布时间】:2019-11-01 22:07:19
【问题描述】:

我正在使用此代码使我的应用程序在更改路线时滚动到顶部,一切正常,但我想在更改查询参数时禁用此选项。我有角度材料选项卡,我的查询参数定义了访问页面时应该打开哪个选项卡,但是当我更改选项卡(也更改 url)时,它会自动滚动到顶部

我认为这是不可能的,但也许你有答案

  imports: [RouterModule.forRoot(routes, {
    scrollPositionRestoration: 'enabled',
    anchorScrolling: 'enabled'
  })]

我希望只更改标签时应用不会滚动到顶部

【问题讨论】:

标签: angular parameters tabs router


【解决方案1】:

查看属性scrollPositionRestoration 文档,发现:

您可以通过调整启用的行为来实现自定义滚动恢复行为...

实施:

  1. 删除添加的代码:
{
  scrollPositionRestoration: 'enabled',
  anchorScrolling: 'enabled'
}

保留为:

imports: [RouterModule.forRoot(routes)]
  1. 将以下代码添加到app.module.ts:
import { Event, Scroll, Router } from '@angular/router';
import { ViewportScroller } from '@angular/common';

export class AppModule {
  constructor(router: Router, viewportScroller: ViewportScroller) {
    router.events.pipe(
      filter((e: Event): e is Scroll => e instanceof Scroll)
    ).subscribe(e => {
      // here you'll have your own logic, this is just an example.
      if (!router.url.includes('hello')) {
        viewportScroller.scrollToPosition([0, 0]);
      }
    });

  }
}

这里是DEMO,用于重现您的问题。

这是一个DEMO 用这个解决方案解决它。

干杯

【讨论】:

  • 只有当路由(不是查询参数)改变时才可以滚动?
  • @Marek 您可以将过滤器更改为filter((e: Event): e is NavigationEnd => e instanceof NavigationEnd )
【解决方案2】:

最后我找到了在查询参数更改here987654321@时不滚动的工作解决方案

在过滤器旁边使用成对管道运算符非常酷,它可以让您将匹配过滤器的最后一个发出的值与当前的值进行比较。

我自己的完整工作 sn-p:

export class AppModule {
  constructor( private router: Router, private viewportScroller: ViewportScroller ) {
    this.router.events.pipe(
      filter( ( e: Event ): e is Scroll => e instanceof Scroll ),
      pairwise()
    ).subscribe( ( eventPair ) => {
      const previousEvent = eventPair[ 0 ];
      const event = eventPair[ 1 ];
      if ( event.position ) {
        // backward navigation
        this.viewportScroller.scrollToPosition( event.position );
      } else if ( event.anchor ) {
        // anchor navigation
        this.viewportScroller.scrollToAnchor( event.anchor );
      } else {
        // forward navigation
        if ( (previousEvent.routerEvent.urlAfterRedirects.split( '?' )[ 0 ]) !== event.routerEvent.urlAfterRedirects.split( '?' )[ 0 ] ) {
          // Routes don't match, this is actual forward navigation
          // Default behavior: scroll to top
          this.viewportScroller.scrollToPosition( [0, 0] );
        }
      }
    } );
  }
}

【讨论】:

    猜你喜欢
    • 2021-09-30
    • 2018-06-24
    • 2019-10-24
    • 2020-08-08
    • 2018-04-01
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多