Angular: Prevent route change if any changes made in the view

后端 未结 4 929
余生分开走
余生分开走 2021-02-06 23:31

If I have a form in a view (Angular). When user tries to navigate away from there, and I want a confirmation message to appear. How can I do that?

4条回答
  •  迷失自我
    2021-02-07 00:27

    If your site needs prevent route change for multiple pages, i suppose it might be convenient to use this service:

    import { Injectable } from '@angular/core';
    import { CanActivateChild } from '@angular/router';
    
    
    @Injectable()
    export class NavPreventerService implements CanActivateChild {
      locks: any = {};
    
      constructor() {
        // Bonus: If necessary also prevent closing the window:
        window.addEventListener('beforeunload', (event) => {
          if (this.hasRoutingLocks()) {
            event.preventDefault();
            event.returnValue = '';
          }
        });
      }
    
      canActivateChild() {
        if (this.hasRoutingLocks()) {
          if (confirm('Leave site?')) {
            this.removeAllRoutingLocks();
            return true;
          }
          return false;
        }
        return true;
      }
    
      setRoutingLock(key: string) {
        this.locks[key] = true;
      }
    
      removeRoutingLock(key: string) {
        delete this.locks[key];
      }
    
      removeAllRoutingLocks() {
        this.locks = {};
      }
    
      hasRoutingLocks(): boolean {
        return !!Object.keys(this.locks).length;
      }
    }
    

    When it is necessary to prevent navigation, then in your component call

    this.navPreventer.setRoutingLock('quiz-form');
    

    Your application routing file should be like this:

    export const appRoutesLocal: Routes  = [
      {path: '', canActivateChild: [NavPreventerService], children: [
        {path: '', component: HomePageComponent},
      ]}
    ];
    

提交回复
热议问题