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

后端 未结 4 928
余生分开走
余生分开走 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:11

    In My example site the user should verify secure pin while navigating to his/her Personal Details page. For all other pages user don't need secure pin. After Secure pin verification success then only he should navigate to "Personal Details" otherwise the user should be in same page.

    private routerChangeListener() {
      this.router.events.subscribe(event => {
        if (event instanceof NavigationStart) {
          this.isPersonalDetailsNavigation(event.url);
        }
       });
    }
    
    private verfiyIsNavigatingToMedication(url: string) {
       url = url.replace('/', '');
       if (url === 'personal-details') {
        showPinVerficationPopup();
       } else {
        console.log('This Is Not Personal Details Page Navigation');
       }
    }
    
    private showPinVerficationPopup() {
      if(verificationSuccess) {
        // This Will Navigate to Personal Details Page
        this.router.navigate(['personal-details']); 
      } else {
        // This Will Prevent Navigation
        this.router.navigate([this.router.url]); 
      } 
    }
    

提交回复
热议问题