[IONIC 4] Tabs, scroll to the top when already in the page?

Hi,

Before i was on Ionic V3 and i used this method to scroll to the page when i was already on the tab pressed and thas was perfect but now on Ionic V4 is not working anymore the “IonSelected” is not working at all.

Any idea on how i can do ?

Code :

import { IonContent } from ‘@ionic/angular’;

@ViewChild(IonContent) content: IonContent;

ionSelected() {
  this.content.scrollToTop(); // 300ms
}
1 Like

Create a service

export interface UrlChangeEvent {
  prevUrl: string;
  currUrl: string;
}
@Injectable({
  providedIn: 'root'
})
export class RouterExtService {
  private urlChangeEventSubject = new Subject<UrlChangeEvent>();
  public urlChangeEvent$ = this.urlChangeEventSubject.asObservable();
  constructor(
    private router: Router
  ) {
    this.router.events.pipe(
      filter(e => e instanceof RoutesRecognized),
      pairwise())
      .subscribe((event: any[]) => {
        this.urlChangeEventSubject.next({
          prevUrl: event[0].urlAfterRedirects,
          currUrl: event[1].urlAfterRedirects
        });
      });
  }
}

In your tab page

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

    this.routerExtService.urlChangeEvent$
      .pipe(takeUntil(this.destroyed$))
      .subscribe((event: UrlChangeEvent) => {
        if (event.prevUrl === event.currUrl
          && event.prevUrl === '<my tab page url>') {
          this.content.scrollToTop(300);
        }
      });