Die*_*erl 42 lifecycle angular
在Angular2中是否有像window.onbeforeunload这样的生命周期钩子?我已经google搜索并在stackoverflow上搜索,但一无所获
Gün*_*uer 61
<div (window:beforeunload)="doSomething()"></div>
Run Code Online (Sandbox Code Playgroud)
要么
@Component({
selector: 'xxx',
host: {'window:beforeunload':'doSomething'}
..
)}
Run Code Online (Sandbox Code Playgroud)
要么
@Component({
selector: 'xxx',
..
)}
class MyComponent {
@HostListener('window:beforeunload')
doSomething() {
}
}
Run Code Online (Sandbox Code Playgroud)
这是如何倾听全球事件.我不知道在将返回值用作构造对话框的文本时是否支持此事件的特殊行为.
你仍然可以使用
export class AppComponent {
constructor() {
window.onbeforeunload = function(e) {
return 'Dialog text here.';
};
}
}
Run Code Online (Sandbox Code Playgroud)
像这里解释的那样https://developer.mozilla.org/de/docs/Web/API/WindowEventHandlers/onbeforeunload
Avi*_* P. 53
GünterZöchbauer的答案在两个方面略有错误,这对我有用:
@Component({
selector: 'xxx',
..
)}
class MyComponent {
@HostListener('window:beforeunload', ['$event'])
doSomething($event) {
if(this.hasChanges) $event.returnValue='Your data will be lost!';
}
}
Run Code Online (Sandbox Code Playgroud)
与Günter的答案有两个主要区别:
@HostListener应该window:beforeunload而不是的论点window:onbeforeunload$event.returnValue替代小智 12
这对我有用。在页面组件构造函数中定义
window.addEventListener("beforeunload", (event) => {
event.preventDefault();
event.returnValue = "Unsaved modifications";
return event;
});
Run Code Online (Sandbox Code Playgroud)
returnValue仅当您想在卸载前提示用户时才定义。
仅当用户与页面交互(例如单击)时才工作。
iOS重要提示
该beforeunload事件不应该发生 - 大概是由于多年来“滥用”的程度很高。
这是Page visibilityAPI 的一部分。
https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
所以我似乎无法pagehide在桌面 chrome 上触发,我也无法beforeunload在 iOS Safari 上触发 - 所以你需要两者 - 但确保不要两次触发你的代码。
@HostListener('window:beforeunload')
@HostListener('window:pagehide')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43427 次 |
| 最近记录: |