Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to specific Expansion Panel in Material Accordion after Component loaded

We are trying to scroll to a specific <mat-expansion-panel> item within a <mat-accordion>. The problem is that ngAfterViewInit() is triggered before the accordion and its panels are fully loaded. This means the scrollIntoView() function is called while the accordions are being loaded and the page size afterwards change making our scroll operation take us to the wrong position of the page.

We also tried the other lifecycle hooks, which did not help, since they're all called to early. Does somebody have any good practice for this issue?

Our source is simple since we are trying to implement something very basic:

landingpage.component.html

<mat-accordion>
   <mat-expansion-panel id="pangel-1">
    <mat-expansion-panel-header>
      <mat-panel-title>Lorem ipsum</mat-panel-title>
    </mat-expansion-panel-header>
    <p>
      Lorem ipsum dolor sit amet,
      consetetur sadipscing elitr,
      sed diam nonumy eirmod tempor invidunt...
    </p>
  </mat-expansion-panel>
  <mat-expansion-panel id="panel-2">
    <mat-expansion-panel-header>
      <mat-panel-title>Lorem ipsum</mat-panel-title>
    </mat-expansion-panel-header>
    <p>
      Lorem ipsum dolor sit amet,
      consetetur sadipscing elitr,
      sed diam nonumy eirmod tempor invidunt...
    </p>
  </mat-expansion-panel> 

  [ ... ] // more panels

</mat-accordion>

landingpage.component.ts

ngAfterViewInit() {
  this.scroll("panel-1");
}

scroll(id) {
  console.log(`scrolling to ${id}`);
  let el = document.getElementById(id);
  el.scrollIntoView();
}
like image 387
Entertain Avatar asked Nov 13 '18 11:11

Entertain


2 Answers

Here is an example on StackBlitz with Angular Material 7. Your technique works fine, but you need to be careful about a couple of things - make sure that the page is long enough so that the panel can be positioned at the top of the page, and make sure you don't misspell the panel's id.

like image 83
G. Tranter Avatar answered Nov 15 '22 05:11

G. Tranter


In my example i click something and it opens a side nav that takes up half the screen, so on the click function i have this logic:

if ($event) {
    setTimeout(() => $event.target.scrollIntoView({behavior: 'smooth', block: 'end'}), 1);
}

So in your example you could tie to the afterExpand event (on mat-expansion-panel) and run the logic.

like image 29
Tim.Burnell Avatar answered Nov 15 '22 04:11

Tim.Burnell