Angular 2 - 如果触摸页面,则在离开页面之前提醒用户

时间:2017-07-19 14:54:12

标签: angular

我们有要求我们必须提醒用户是否触摸了页面,如果使用选择不同的菜单应用程序应显示警告,如果用户继续继续,则应显示警告,然后只应重定向,否则它应该回退到同一页面。我们已尝试使用ngOnDestroy但是,应用程序正在重定向到下一页而不显示警报。

我的第一个方法是:

 ngOnDestroy()
{        
    this.touched = this.eventForm.touched;
    if (this.touched)
        this.display = true;
}

现在我正在尝试使用CanDeactivate后卫(请参阅this plunker示例):

import { Injectable } from '@angular/core'; 
import { CanDeactivate } from '@angular/router'; 
import { SidebarComponent } from './shared/sidebar/sidebar.component'; 

@Injectable() 
export class ConfirmDeactivateGuard implements CanDeactivate<SidebarComponent> {
     canDeactivate(target: SidebarComponent) { 
          if (target.hasChanges()) { 
               return window.confirm('Do you really want to cancel?'); 
          } 
          return true; 
      } 
}

1 个答案:

答案 0 :(得分:4)

您应该使用canDeactivate后卫

docs

https://angular.io/api/router/CanDeactivate

import { Injectable } from '@angular/core'; 
import { CanDeactivate } from '@angular/router'; 
import { SidebarComponent } from './shared/sidebar/sidebar.component'; 

@Injectable() 
export class ConfirmDeactivateGuard implements CanDeactivate<SidebarComponent> {
     canDeactivate(target: SidebarComponent) { 
          if (target.hasChanges()) { 
               return window.confirm('Do you really want to cancel?'); 
          } 
          return true; 
      } 
}

参考Sample @plnkr https://blog.thoughtram.io/angular/2016/07/18/guards-in-angular-2.html