How to detect if user swipes for browser back navigation

Viewed 952

I have an Angular application with some router animations. When navigation from A to B, this looks as intended. When navigating back from B to A by clicking an in-app back button or a browser back button, the reversed animation also looks good.

The issue arises when a mobile user navigates back from B to A by using a swipe gesture. The swipe itself creates a sort of animation (revealing the previous page ase you slide your finger), but after this navigation has ended, my in-app animations still trigger, which looks pretty jarring.

Is there a way to detect if the user performed the back navigation by swiping so I can disable my Angular animations?

2 Answers

you can detect back navigation like this by subscribing to router events, and check the navigationTrigger if it's equal to "postate" it's a back navigation

router.events.pipe(
  filter(( event: NavigationEvent ) => {
             return( event instanceof NavigationStart );
})).subscribe(( event: NavigationStart ) => {
     if(event.navigationTrigger === "popstate") {
        //means it's a back navigation
     }       
});

here is the NavigationStart class from angular docs for more details

class NavigationStart extends RouterEvent {
 constructor(id: number, url: string, navigationTrigger: "imperative" | 
 "popstate" | "hashchange" = 'imperative', restoredState: { [k: string]: any; 
 navigationId: number; } = null)
 navigationTrigger?: 'imperative' | 'popstate' | 'hashchange'
 restoredState?: {...}
 toString(): string

 // inherited from router/RouterEvent
 constructor(id: number, url: string)
 id: number
 url: string
}
Related