1

I need to restrict the backspace navigation within my whole app.Are there any solutions i.e something that I can perform under a single tile for my whole app ?

Suhag Lapani
  • 655
  • 10
  • 18
  • Possible duplicate of [Prevent backspace from navigating back in AngularJS](https://stackoverflow.com/questions/29006000/prevent-backspace-from-navigating-back-in-angularjs) – laminatefish Mar 21 '18 at 09:52
  • @LokiSinclair it is not duplicate becuse of this question is related to angular2/4/5 not for angularjs. – Suhag Lapani Mar 21 '18 at 09:58
  • But it is a duplicate of this, which has an answer - use canDeactivate guard. https://stackoverflow.com/questions/36357204/how-to-disable-browser-back-button-in-angular-2 – rmcsharry Mar 21 '18 at 11:16
  • @Shiv the solution may be slightly different, but the problem is the same. Adapt the solution to work in Angular5 = Profit! – laminatefish Mar 21 '18 at 11:23

3 Answers3

7

I am working on Angular 6 application and was facing same issue on Internet Explorer (IE).

I was searching the solution on internet then I found one solution in JQuery. Somehow I managed to convert it in Angular.

This snippet resolved the issue.

@HostListener('document:keydown', ['$event'])
  onKeyDown(evt: KeyboardEvent) {
    if (
        evt.keyCode === 8 || evt.which === 8
    ) {
      let doPrevent = true;
      const types =['text','password','file','search','email','number','date','color','datetime','datetime-local','month','range','search','tel','time','url','week'];
      const target = (<HTMLInputElement>evt.target);

  const disabled = target.disabled || (<HTMLInputElement>event.target).readOnly;
  if (!disabled) {
    if (target.isContentEditable) {
      doPrevent = false;
    } else if (target.nodeName === 'INPUT') {
      let type = target.type;
      if (type) {
        type = type.toLowerCase();
      }
      if (types.indexOf(type) > -1) {
        doPrevent = false;
      }
    } else if (target.nodeName === 'TEXTAREA') {
      doPrevent = false;
    }
  }
  if (doPrevent) {
    evt.preventDefault();
    return false;
  }
  }
  }
Vijay Gawade
  • 94
  • 1
  • 3
  • 1
    Very helpful, thank you. The only thing I changed in my implementation is removed `keyCode` and `which` references, because they are both deprecated. Instead, I'm checking if `$event.key == 'Backspace'`. – Kon Oct 16 '19 at 18:10
  • 1
    Nice one, It really works for me. I found the above mentioned issue in Firefox – Varinder Singh Baidwan Nov 21 '19 at 06:05
1

The solution LokiSinclair proposed for AngularJS should be adjustable to work with Angular 5 as well. The basic solution just prevents the key event, therefore you could enter a HostListener to your AppComponent which handles this globally:

@HostListener('document:keydown', ['$event'])
onKeyDown(evt: KeyboardEvent) {
  if (
    evt.which === 8 && 
    ( evt.target.nodeName !== "INPUT" && evt.target.nodeName !== "SELECT" ) 
  ) { 
    evt.preventDefault();
  }
}

Credits to Prevent backspace from navigating back in AngularJS for the general logic, just translated it to the Angular 5 utilities.

OClyde
  • 1,036
  • 6
  • 11
0

With Router Guards we can prevent users from accessing areas that they’re not allowed to access, or, we can ask them for confirmation when leaving a certain area.To control whether the user can navigate to or away from a given route, use these route guards.

You can use any of these two:

CanActivate Checks to see if a user can visit a route.

CanDeactivate Checks to see if a user can exit a route.

Here your preference is not to allow to to go back. I have used for a login condition. I am giving my sample code to you. It may help you.

       import { Injectable } from '@angular/core';
      import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
      import { AuthenticateService } from '../authenticate.service';
      import { Observable } from 'rxjs';

      @Injectable({
        providedIn: 'root'
      })
      export class LoginAuthService implements CanActivate {

        constructor(
          private checkLogin: AuthenticateService,
          private router: Router) { }
        canActivate(
          route: ActivatedRouteSnapshot,
          state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
            // This isLoggedIn flag is set when the token is found after login
            if (!this.checkLogin.isLoggednIn()) {                 
              return true;
            } else {
              this.router.navigate(['/componentOfMyChoice']);
            }

        }
      }

Then I used it in the routing like this

    { path: 'login', component: LoginComponent , canActivate: [LoginAuthService]},

So when a user is logged in you cannot go back to the login page until and unless you get logged out. Hope it will help you

Abhiz
  • 970
  • 1
  • 16
  • 36