angularprimengprimeng-datatable

Scroll to top function in angular with primeng table not working


I have the following issue:

I have implemented a paginated table in Angular using PrimeNG. When switching the page, I want it to automatically scroll to the top.

I have already tried window.scroll and the ViewportScroller, but neither has any effect on the scrolling behavior.

Since my page consists of various components, I believe it has to do with the element that should be scrolled.

Is there a way to generally find the scrolling element and then set it to the top of the page?

app.component.html

<div slot="content" class="w-full">
        <router-outlet></router-outlet>
 </div>

manual-search.component.ts
This component is rendered inside the router outlet, streching the conten slot downwords. After emiting the onPageChange event I would like to navigate to the top of the page

public onPageChange(event: Observable<any>, type: 'Card' | 'Ticket') {
    event.subscribe((data) => {
      if (type == 'Card') {
        this.cards$.next(data);
      } else {
        this.tickets$.next(data);
      }
    });
  }

Solution

  • Maybe this question can help you.

    For this you need to enable anchorScrolling in you RouterModule config

    @NgModule({
      declarations: [],
      imports: [
        RouterModule.forRoot(
          appRoutes,
          {
            anchorScrolling: "enabled"
          }
        )
      ],
      exports: [
        RouterModule
      ]
    })
    

    Then you need to import the Router in your component and use the Router.navigate function and define an id for the element you want to scroll to

    this.router.navigate([], { fragment: 'fragmentIdToScrollTo' })
    

    HTML

    <div id='fragmentIdToScrollTo'></div>