[英]Call a function when user closes tab in angular
I would like to call a function when user closes the tab.当用户关闭选项卡时,我想调用 function。 I have used hostlistener to fire a event when user closes the tab and a popup appears with cancel and leave button.当用户关闭选项卡并出现带有取消和离开按钮的弹出窗口时,我使用主机监听器触发事件。 I need to call a function when user clicks the leave button.当用户单击离开按钮时,我需要调用 function。 Below is the code I have written and I need to call myFunction() when user clicks on leave button.下面是我编写的代码,当用户单击离开按钮时,我需要调用 myFunction()。
@HostListener('window:beforeunload', ['$event'])
beforeunloadHandler(event) {
event.preventDefault();
return false;
}
myFunction(){
//code
}
You can try ngOnDestroy if you are changing tab then this method will invoke and you can call your function!!如果您正在更改选项卡,您可以尝试 ngOnDestroy 然后此方法将调用,您可以调用您的函数!
ngOnDestroy(): void { enter code here
} ngOnDestroy(): void { enter code here
}
There are two ways to the listener to the event of closing tab in your class, by calling your function with the key this
.有两种方法可以监听 class 中关闭选项卡的事件,方法是使用键this
调用 function。
@HostListener('window:unload', [ '$event' ])
beforeUnloadHandler(event) {
this.myFunction(event)
event.preventDefault();
return false;
}
unloadHandler(event) {
this.myFunction(event)
// ...
}
myFunction(event){
console.log("this event come form: ", event)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.