我有一个页面,它有一个表单,可以在用户离开之前检查用户是否有未保存的更改。
问题是,即使使用 preventDefault() 并返回 false,用户仍然可以单击远离组件。
有没有办法防止 ngOnDestroy 或 click 事件发生?
注意:用户不会去不同的路线,只是来自同一组件的另一个选项卡。
ngOnDestroy() {
if (this.myForm.dirty) {
let save = confirm('You are about to leave the page with unsaved changes. Do you want to continue?');
if (!save) {
window.event.preventDefault();
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud) 我有一个<iframe>内部有一个元素的组件。
该组件被称为路线。
当调用组件时,<iframe>元素会重新加载内容,但我只需要加载该内容一次。为此,我需要取消该组件的销毁。
我尝试在调用时将其移动<iframe>到<body>元素onDestroy,并在再次调用该组件时重用它,但是当您将 an 移动<iframe>到另一个父级时,他的内容将重新加载。
有人知道如何做到这一点吗?
在下面的代码中("使用TypeScript进行Angular 2开发"一书中的示例):
import {CanDeactivate, Router} from "@angular/router";
import {Injectable} from "@angular/core";
@Injectable()
export class UnsavedChangesGuard implements CanDeactivate{
constructor(private _router:Router){}
canDeactivate(){
return window.confirm("You have unsaved changes. Still want to leave?");
}
}
Run Code Online (Sandbox Code Playgroud)
当我将鼠标悬停在WebStorm中的CanDeactivate上时,我看到一个警告:
参考这个问题的答案 - 通用类型'Observable <T>'需要1个类型参数 - 以下更改将删除警告:
export class UnsavedChangesGuard implements CanDeactivate<any>{
Run Code Online (Sandbox Code Playgroud)
但是,我想知道如何找出CanDeactivate所需的实际参数.
编辑:看@ angular/router/src/interfaces.d.ts,我们可以看到以下内容:
/**
* @whatItDoes Indicates that a class can implement to be a guard deciding if a route can be
* deactivated.
*
* @howToUse
*
* ```
* class UserToken {}
* …Run Code Online (Sandbox Code Playgroud)