Nagesh Katke
Nagesh Katke

Reputation: 578

Change route using browser back button in angular 6

I have an website in angular6 and I want to change URL on click of browser back button using onPopState but its not working. TS file of desired route component load but failing to stay and gets redirected as per browser history.

I am using below code

constructor(private fb: FormBuilder, 
    private _phonenumberService: PhonenumberService, 
    private router: Router, 
    private apiService: ApiServiceService, 
    public location: Location, 
    public plocation: LocationStrategy) {
            this.plocation.onPopState(() => {
              console.log('Back button pressed');
              this.router.navigate(['/home'],  {replaceUrl:true});
          });

Thanks in advance.

Upvotes: 2

Views: 10451

Answers (1)

hrdkisback
hrdkisback

Reputation: 908

Try this one. Import HostListener

import { Component, HostListener } from '@angular/core';

And then bind event

@HostListener('window:popstate', ['$event'])
onBrowserBackBtnClose(event: Event) {
    console.log('back button pressed');
    event.preventDefault(); 
    this.router.navigate(['/home'],  {replaceUrl:true});
}

Upvotes: 4

Related Questions