Angular:如何停止浏览器刷新而不使用确认或警报来显示自定义模式(例如未保存的更改)

问题描述 投票:0回答:1

enter image description here我需要根据未保存的表单显示模态sample code更改它按角度路线的预期工作

问题:浏览器刷新/后退按钮/手动更改网址时弹出窗口不起作用

解决方案: 如何在不使用确认框或警报的情况下停止浏览器引用, 我们如何在页面卸载时手动刷新页面时显示引导模式

我希望手动更改网址后页面不会刷新,并且应该显示自定义组件模式

javascript reactjs angular angular-ui-router
1个回答
0
投票

为了防止这种重新加载,您可以使用 Angular 的

CanDeactivate
路由防护以及模式对话框。以下是实现这一目标的方法:

1- 首先,为您的模式对话框创建一个自定义组件。当有未保存的更改时,这将用作确认对话框。例如,您可以创建一个名为

UnsavedChangesDialogComponent
的组件。

2- 接下来,创建 Routeguard 以检查未保存的更改。您可以使用

CanDeactivate
路线守卫来实现此目的。

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

export interface CanComponentDeactivate {
  canDeactivate: () => boolean;
}

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

3- 在有未保存更改的表单中实现

canDeactivate
方法。此方法接受 true 或 false。根据是否有变化返回 true 或 false。

import { Component } from '@angular/core';

@Component({
  selector: 'app-form-component',
  templateUrl: 'form-component.html',
})
export class YourFormComponent {
  // ...

  canDeactivate(): boolean {
    if (this.formChanged) {
      // Display the modal dialog
      // Return false to prevent navigation
      this.showUnsavedChangesModal();
      return false;
    }
    return true;
  }

  private showUnsavedChangesModal() {
    // Use a service to open your custom modal component
    // ...
  }
}

4- 最后,将 UnsavedChangesGuard 应用到您想要防止未保存更改的导航的路线。

const routes: Routes = [
  {
    path: 'your-form',
    component: YourFormComponent,
    canDeactivate: [UnsavedChangesGuard], // This is the code that checks
  },
  // ...other routes
];
  
© www.soinside.com 2019 - 2024. All rights reserved.