Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IONIC 4 scroll to top when clicking on tab button

i need to scroll to the top of the page when i click a tab button and i am already in this page

i tried:

 @ViewChild(IonContent,  { static: false }) private content: IonContent;

myMethod() {
 this.content.scrollToTop();
}

but this does not work and i tried putting this in the ioViewWillEnter in the target page and still it only works for the first time in ionic 4

i also tried putting it in the ionTabsDidChange event of the ion tab but this event is only triggered if the tabs change

like image 957
Hanna Avatar asked Sep 18 '25 20:09

Hanna


1 Answers

I think that you've requested a tricky operation, as that is not the standard way of doing things.

Normally the button does nothing which makes the user realise they are already on that tab.

I set up a demo project and tried the different built-in events but ultimately the tab-button emits the click event and it gets as far as the shouldChange method in the tabs component before being dismissed for being the same tab:

https://github.com/ionic-team/ionic/blob/master/core/src/components/tabs/tabs.tsx#L164

What does work is adding a click event to your tab button in tabs.page.html:

<ion-tabs>
  <ion-tab-bar slot="bottom">
    {{ snip }}

    <ion-tab-button tab="tab2" (click)="tabButtonClicked('tab2')">
      <ion-icon name="apps"></ion-icon>
      <ion-label>Tab Two</ion-label>
    </ion-tab-button>

    {{ snip }}
  </ion-tab-bar>

</ion-tabs>

I think by using that click handler you grab the current tab, and dispatch your own event:

tabButtonClicked(tabNumber: string) {
    if (tabNumber === this.selectTab) { 
        this.events.publish('tabs', tabNumber); 
    }
}

This guide shows how to use the Ionic Events system, which lets you pass custom events to other components in the system:

https://alligator.io/ionic/events/

So you can use this to emit a custom "scroll to top" event, and handle that inside the tab. Then use your original .scrollToTop() code inside that custom event handler.

For example in in the tab page you want to scroll add:

@ViewChild(IonContent, { static: false }) private content: IonContent; 

constructor(public events: Events) { 
}

ionViewWillEnter() {
    this.events.subscribe('tabs', tabNumber => {
        if (tabNumber === 'tab1') { 
            this.content.scrollToTop(); 
        } 
    });
}

ionViewDidLeave() {
    this.events.unsubscribe('tabs', () => {} );
}
like image 120
rtpHarry Avatar answered Sep 21 '25 05:09

rtpHarry