[removed] - Importing in Angular2

前端 未结 2 1749
栀梦
栀梦 2021-01-24 01:57

I am trying to use window.onbeforeunload in my project but I do not know how to use it.

I have tried in 2 ways:

1st way

<         


        
相关标签:
2条回答
  • 2021-01-24 02:32

    you have to import @HostListener and use it like below in your component

    import { Component, OnInit, HostListener } from '@angular/core';
    
    export class TestComponent implements OnInit {
        @HostListener('window:beforeunload', ['$event']) onBeforeUnload(event) {
               // do something here 
              console.log("method called");
        }
    }
    
    0 讨论(0)
  • 2021-01-24 02:50

    create a file beforeunload.js that you put in the assets folder, containing

    window.beforeunload = function() {
      // Do your stuff
    }
    

    In your angualr-cli.json, simply import the file :

    "scripts": [
      "assets/beforeunload.js"
    ],
    
    0 讨论(0)
提交回复
热议问题