[Tabs] Automatically page scrolls to top when switching between some tabs
Bug, feature request, or proposal:
We found a bug. We had top content and a tab group below this content. And then we scrolled a little bit to bottom. We switched between some tabs. Now, page scrolled to top automatically.
It only occurs when we have top content on this page.
What is the expected behavior?
Page should keep scroll position when switching some tabs
What is the current behavior?
Page scrolls to top when switching some tabs
What are the steps to reproduce?
-Step 1: Scroll a little bit to bottom on page -Step 2: Click on Tab 3 The page will scroll to top.
Demo here: https://stackblitz.com/edit/angular-wjtrxy
What is the use-case or motivation for changing an existing behavior?
A bug
Which versions of Angular, Material, OS, TypeScript, browsers are affected?
Angular 5.0.3 - Material 5.0.2 - Window 10 - Typescript 2.4.2
Is there anything else we should know?
Thanks a lot!
I might have a solution for this. Its a crude solution, but is seems to be working, at least for me it does :) So let me explain:
You need a parent component, which has the entire mat-tab-group code, and child components, for each individual mat-tab body (I suppose you can do without parent/child as well).
Parent component HTML:
<mat-tab-group (selectedTabChange)="forceScrollPosition($event)">
<mat-tab>
<app-tab-child-0
[scrollPosition]="scrollChild0"
[canUpdateScroll]="updateChild0Scroll"
(scrollChanged)="scrollChanged($event)">
</app-tab-child-0>
</mat-tab>
<mat-tab>
<app-tab-child-1
[scrollPosition]="scrollChild1"
[canUpdateScroll]="updateChild1Scroll"
(scrollChanged)="scrollChanged($event)">
</app-tab-child-1>
</mat-tab>
</mat-tab-group>
Parent component TS:
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-tab-parent',
templateUrl: './app-tab-parent.html',
styleUrls: ['./app-tab-parent.scss']
})
export class ParentComponent implements OnInit {
// Hold scroll positions for each child (can be also array of values, it doesnt matter)
scrollChild0: number = 0;
scrollChild1: number = 0;
// Permission for child component to emit scroll change
updateChild0Scroll: boolean = true; //The FIRST tab displayed should have this attribute set to ,,true"
updateChild1Scroll: boolean = false;
// There are several ways to trigger method in child, I prefer this one
@ViewChild(TabChild0Component) private tabChild0Component: TabChild0Component;
@ViewChild(TabChild1Component) private tabChild0Component: TabChild1Component;
//Here set new scroll position for specific child tab
public scrollChanged(event: any) {
//example
if(event.index === 0) {
this.scrollChild0 = event.value;
}
else if ...... {
....
}
}
// When selected tab is changed, revalidate permissions and force child to load latest scroll
public forceScrollPosition(event: any) {
//example
this.updateChild0Scroll= event.index === 0;
this.updateChild1Scroll= event.index === 1;
....
// now you need to identify selected tab and force child component to load last saved scroll
if(event.index === 0) {
this.tabChild0Component.loadScroll();
}
else if ...... {
....
}
}
}
Child component TS:
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-tab-child-0',
templateUrl: './app-tab-child-0.html',
styleUrls: ['./app-tab-child-0.scss']
})
export class TabChild0Component implements OnInit {
@Input() scrollPosition: number;
@Input() canUpdateScroll: boolean;
@Output() scrollChanged = new EventEmitter();
// This path targets mat tab body. the ,,#mat-tab-content-0-0" needs to be changes, depending on
// child index position in the tabs (#mat-tab-content-0-0, #mat-tab-content-0-1, ...)
private readonly elementPath = "#mat-tab-content-0-0 .mat-tab-body-content.ng-trigger.ng-trigger-translateTab";
ngOnInit() {
let element = document.querySelector(this.elementPath);
let base = this;
if(element) {
element.addEventListener('scroll', function() {
// Check if this child is currently focused tab, otherwise it emits 0 by default and defeats the whole
// purpose
if(base.canUpdateScroll) {
base.scrollChanged.emit(document.querySelector(base.elementPath).scrollTop);
}
});
}
}
/** Load last known scroll position */
public loadScroll() {
let element = document.querySelector(this.elementPath);
if(element) {
document.querySelector(this.elementPath).scrollTop = this.scrollPosition;
}
}
}
Again, sorry for the crude code, but I hope it can give you at least some basic idea of my solution. If it will be helpful to anyone, well, I am glad I could help :)
https://stackblitz.com/edit/angular-wjtrxy-g4ksm6
Add a min-height="800px" to parent elemnt of mat-tab-group. :)
Thank you, I solved scroll to top of page issue using this code 👍
Especially bad with variable tab content as min-height and padding hacks are not working.
It would be great to get an update on this.
I was able to use min-height: 100% on the parent with no other styling.
Still have this problem. Angular material 8.2.1
Still a problem in 2020.
less min-height: 500px or 400px works too...
This is super-frustrating, and min-height is absolutely a hack (more power to you if it works for your situation though.)
min-height does exactly what you expect here, which is a problem for both static and dynamic tab contents. Say I have three tabs, A, B, and C, with "natural" (fits content, looks good, i.e. what the dev wants) heights of 600px, 800px, and 200px, respectively. Say I also have content above the tab group such that there's about 220px left "before the fold" (bottom of viewport) on a desktop browser. A min-height: 200px will respect the min height of my component, but switching between tabs A and B while viewing them in full will always bounce to the top. Increasing min-height any more will start adding extra whitespace to tab C, which could be perfectly acceptable, or could look like trash.
No one adequately explained what's going on, in my opinion, so here's an illustrative demo: https://stackblitz.com/edit/angular-material-bouncing-tabs?file=app%2Fbouncing-tabs-demo.html
There's an object with property, matTabsAnimations.translateTab, that forces a min height of 1px for some issues. If that instead chose the height of the previous tab, I think that would solve things. That would eliminate this hidden third size that causes the jump.
For a slightly better hack, you can target .mat-tab-body-content.ng-trigger-translateTab.ng-animate-queued instead of the containing element. You still have to pick a third size that will potentially cause unexpected jumps, but this doesn't impact the steady-state layout at least. If you give it a fat red border, slow the animation way down, and throttle the CPU down (via the Chrome debugger,) you still won't see it unless you're on that breakpoint.
Still an issue with Angular 9 & Angular Material 9.1.0. Seriously.
Scrolls to top after route change.
- Have a list of brands. 2)Scroll to the middle . Select any brand. Navigates to another route with its description. 3)Click on Back Button. 4)Redirects to the list but scrolls to top.
Still a problem in Angular 7, Material.
Required behaviour: Restore original scroll position.
Any solution?
Made a small directive that retains the scroll position when you change tabs.
import { Directive, ElementRef, OnDestroy } from '@angular/core'
import { fromEvent, Subscription } from 'rxjs'
@Directive({
selector: '[xxxScrollRetainer]'
})
export class ScrollRetainerDirective implements OnDestroy {
private changes: MutationObserver
private lastScrollPosition = 0
private subscription: Subscription
constructor(private elementRef: ElementRef) {
this.changes = new MutationObserver(() => this.rollbackScrollPosition())
this.changes.observe(this.elementRef.nativeElement, { childList: true, subtree: true })
this.subscription = fromEvent(window, 'scroll').subscribe(() => {
this.lastScrollPosition = window.pageYOffset
})
}
private rollbackScrollPosition() {
window.scrollTo(window.pageXOffset, this.lastScrollPosition)
}
ngOnDestroy(): void {
this.subscription.unsubscribe()
this.changes.disconnect()
}
}
The issue is unrelated to UI tab modules, I can confirmed because the same scrolling happened with ngbTab. The issue, for me at least, is storing tab state in the query params.
You can implement custom scroll restoration behavior by adapting the enabled behavior as in the following example. https://angular.io/api/router/ExtraOptions#scrollPositionRestoration
Setting scrollPositionRestoration: 'enabled', solves the issue, but screws up expected behavior in my app everywhere else. Use the custom check option the link above mentions to hack your edge case together.
For context, the min-height does not solve it for me on Angular 9.
The same issue :(
The min height is depend the size of the window no always is needed 800px o 500px etc..
I do that:
Then:

The problem is the little placeholder element before sliding in the next tab. It has a min-height of 1px, and even though it's in and out (and the next tab in the DOM to the side) before you can see it, the scroll change still happens.
If it instead latched the height of the outgoing tab, behavior would be as most people expect.
@jneuhaus20 I dosen't see that, can you send a screenshot ?
@britvik works for me. Thanks.
@britvik Which component do you attach your directive to? I attached it to mat-tab-group that didn't work. Infact, the page didn't load.
@DavidTheProgrammer You can attach it to any element (e.g. div) that contains the tab group.