猿问

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

我每天都看到一些应用程序有一个功能,当你在一个页面上,你正在填写,例如,一个表格,当你尝试点击其他地方,例如在导航菜单中,甚至离开页面时,你有不安全的改变他们询问用户是否想离开页面,如果有人可以向我提供一个如何在 Angular 中实现的示例,我将不胜感激,我不确定这是我正在使用的后端中的前端还是后端作业爪哇。非常感谢,每个想法都很重要:D。



眼眸繁星
浏览 141回答 2
2回答

慕莱坞森

canDeactivate您可以为每个组件使用guard,首先你必须添加这个服务文件“deactivate-guard.service.ts”:import { Injectable } from '@angular/core';import { CanDeactivate } from '@angular/router';import { Observable } from 'rxjs/Observable';export interface CanComponentDeactivate {&nbsp; canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;}@Injectable()export class DeactivateGuardService implements&nbsp; CanDeactivate<CanComponentDeactivate>{&nbsp; canDeactivate(component: CanComponentDeactivate) {&nbsp; &nbsp; return component.canDeactivate ? component.canDeactivate() : true;&nbsp; }}那么你必须在应用程序模块中提供:providers: [&nbsp; &nbsp; DeactivateGuardService&nbsp; ]现在在您要保护的组件中,添加功能:export class ExampleComponent {&nbsp; &nbsp; loading: boolean = false;&nbsp; &nbsp; &nbsp;@ViewChild('exampleForm') exampleForm: NgForm;&nbsp; &nbsp; &nbsp;canDeactivate(): Observable<boolean> | boolean {&nbsp; &nbsp; &nbsp; &nbsp; if (this.loading|| this.exampleForm.dirty) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return this.confirmBox('Discard Unsaved Changes?');&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;return true;&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; confirmBox(message?: string): Observable<boolean> {&nbsp; &nbsp; &nbsp; &nbsp;const confirmation = window.confirm(message || 'Are you sure?');&nbsp; &nbsp; &nbsp; &nbsp;return of(confirmation);&nbsp; &nbsp;};}将指令添加到路由模块中的组件:@NgModule({&nbsp; imports: [&nbsp; &nbsp; RouterModule.forRoot([&nbsp; &nbsp; &nbsp; {&nbsp;&nbsp; &nbsp; &nbsp; path: 'example',&nbsp;&nbsp; &nbsp; &nbsp; canDeactivate: [DeactivateGuardService],&nbsp; &nbsp; &nbsp; component: ExampleComponent&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; ])&nbsp; ]

哆啦的时光机

您可以使用 canDeactivate 守卫检查页面离开并显示您希望显示类似内容的警告消息import { Injectable } from '@angular/core';import { CanDeactivate } from '@angular/router';import { Observable } from 'rxjs/Observable';export interface CanComponentDeactivate {&nbsp; &nbsp; canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;}@Injectable()export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate>{&nbsp; &nbsp; canDeactivate(component: CanComponentDeactivate) {&nbsp; &nbsp; &nbsp; &nbsp; return component.canDeactivate ? component.canDeactivate() : true;&nbsp; &nbsp; }}包括设置可以激活守卫到这样的路线{ path: 'sample-path', component: SampleComponent, canDeactivate: [CanDeactivateGuard] },和组件的 canDeactivate 方法canDeactivate() {&nbsp; &nbsp; &nbsp; &nbsp; if (this.formIsIncomplete > 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let result: boolean = window.confirm("You have unsaved Changes");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return result;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答