Skip to content Skip to sidebar Skip to footer

Detect Back Button Pressed In Angular2

I'm trying to detect if the back button was pressed when I load this component. In the ngOnInit(), I'd like to know if Back was clicked so I don't clear all my filters. Here is the

Solution 1:

In my application I created a NavigationService which contains a flag that can be used to determine if the back button has been pressed.

import { Injectable } from'@angular/core';
import { Router, NavigationStart } from'@angular/router';
import { tap, filter, pairwise, startWith, map } from'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
exportclassNavigationService {
    wasBackButtonPressed = false;

    constructor(private _router: Router) {
        this._router.events.pipe(
            filter(ev => ev instanceofNavigationStart),
            map(ev => <NavigationStart>ev),
            startWith(null),
            pairwise(),
            tap(([ev1, ev2]) => {
                if (!ev1 || (ev2.url !== ev1.url)) {
                    this.wasBackButtonPressed = ev2.navigationTrigger === 'popstate';
                }
            })
        ).subscribe();
    }
}

It is using Rxjs pairwise() operator because I noticed that back button causes NavigationStart event to be sent 2 times, the first one has navigationTrigger = 'popstate' and that is what we're looking for.

Now I can inject this service into my component, and I can reference this flag to determine whether to run special logic if the user arrived there via the browser's back button.

import { Component, OnInit } from'@angular/core';
import { NavigationService } from'src/services/navigation.service';

@Component({
    selector: 'app-example',
    templateUrl: './app-example.component.html',
    styleUrls: ['./app-example.component.scss']
})
exportclassExampleComponentimplementsOnInit {

    constructor(private _navigationService: NavigationService) {
    }

    ngOnInit(): void {
        if (this._navigationService.wasBackButtonPressed) {
            // special logic here when user navigated via back button
        }
    }
}

One other thing to know is, this NavigationService should run immediately at app startup, so it can begin working on the very first route change. To do that, inject it into your root app.component. Full details in this SO post.

Solution 2:

create a variable in service , initialize it to false and set it to true inside the ngOnInit method.Since service gets initialized only once , add in ngOnInit :-

 ngOnInit(){
    if(!this._filterService.flag) this._filterService.clear()
  this._filterService.flag = true;
  //rest of your code
 }

Make sure service is initialized only once ,i.e when app is bootstrapped and not inside component's metadata.If page is refreshed , flag value will be false initially and true if component is accessed using back button

Post a Comment for "Detect Back Button Pressed In Angular2"