Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm developing a web site using Angular 2. Is there any way to disable or trigger Browser back button using Angular 2?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
479 views
Welcome To Ask or Share your Answers For Others

1 Answer

Not sure if this is already sorted, but posting the answer nonetheless, for future references. To tackle this, you basically need to add a listener in your app-component and setup a canDeactivate guard on your angular-router.

// in app.component.ts
import { LocationStrategy } from '@angular/common';

@Component({
  selector: 'app-root'
})
export class AppComponent {
  constructor(
    private location: LocationStrategy
  ) {
    // check if back or forward button is pressed.
    this.location.onPopState(() => {
      // set isBackButtonClicked to true.
      this.someNavigationService.setBackClicked(true);
      return false;
    });
  }
}

// in navigation guard
@Injectable()
export class NavigationGuard implements CanDeactivate<any> {
  constructor(private someNavigationService: SomeNavigationService) {}
  canDeactivate(component: any) {
    // will prevent user from going back
    if (this.someNavigationService.getBackClicked()) {
      this.someNavigationService.setBackClicked(false);
      // push current state again to prevent further attempts.
      history.pushState(null, null, location.href);
      return false;
    }
    return true;
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...