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();
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With