如何制作一个警告框,询问用户是否要离开页面或仅离开角度?

时间:2019-06-27 09:31:13

标签: java angular

我每天都看到某个应用程序具有的功能,例如当您在页面上并且正在填写表格时,并且当您尝试单击其他位置(例如在导航菜单中)甚至离开页面时,进行了不安全的更改,他们询问用户是否要离开该页面,如果有人可以向我提供如何在Angular中实现此功能的示例,我将不胜感激,我不确定这是后端的前端还是后端工作。正在使用Java。非常感谢,每个想法都很重要:D。

3 个答案:

答案 0 :(得分:1)

您可以为每个组件使用canDeactivate保护,

首先,您必须添加此服务文件“ deactivate-guard.service.ts”:

import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs/Observable';

export interface CanComponentDeactivate {
  canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}

@Injectable()
export class DeactivateGuardService implements  CanDeactivate<CanComponentDeactivate>{

  canDeactivate(component: CanComponentDeactivate) {
    return component.canDeactivate ? component.canDeactivate() : true;
  }
}

然后您必须在应用模块中提供

providers: [
    DeactivateGuardService
  ]

现在在要保护的组件中,添加功能:

export class ExampleComponent {
    loading: boolean = false;
     @ViewChild('exampleForm') exampleForm: NgForm;

     canDeactivate(): Observable<boolean> | boolean {

        if (this.loading|| this.exampleForm.dirty) {

           return this.confirmBox('Discard Unsaved Changes?');
       }
       return true;
     }

    confirmBox(message?: string): Observable<boolean> {
       const confirmation = window.confirm(message || 'Are you sure?');

       return of(confirmation);
   };


}

将指令添加到路由模块中的组件:

@NgModule({
  imports: [
    RouterModule.forRoot([
      { 
      path: 'example', 
      canDeactivate: [DeactivateGuardService],
      component: ExampleComponent 
    }
    ])
  ]

答案 1 :(得分:1)

您可以使用canDeactivate保护器检查页面休假并显示您希望显示类似这样的警告消息

import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs/Observable';

export interface CanComponentDeactivate {
    canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate>{
    canDeactivate(component: CanComponentDeactivate) {
        return component.canDeactivate ? component.canDeactivate() : true;
    }
}

包括将可以激活的警戒设置为这样的路线

{ path: 'sample-path', component: SampleComponent, canDeactivate: [CanDeactivateGuard] },

以及组件的canDeactivate方法

canDeactivate() {
        if (this.formIsIncomplete > 0) {
            let result: boolean = window.confirm("You have unsaved Changes");
            return result;
        }
        return true;
    }

答案 2 :(得分:1)