How to prevent page refresh in angular 4

RajnishCoder picture RajnishCoder · Nov 16, 2017 · Viewed 33.5k times · Source

I want to prevent page refresh by everywhere.

I tried the code below

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { CommonServices } from '../services/common.service'; 

@Component({
  selector: 'app-review-prescription',
  templateUrl: './review-prescription.component.html',
  styleUrls: ['../../assets/css/prescriptionView.css'],
  providers:[
    CommonServices
  ]
})
export class ReviewPrescriptionComponent implements OnInit {
    constructor(
        private commonServices:CommonServices,
        private router:Router
        ){}
    ngOnInit(){
      window.onbeforeunload = function(event) {
        return 'By refreshing this page you may lost all data.';
      }
  }

}

Tried this on ngOnChanges(), ngOnInit(), ngOnDestroy() even outside the component class(sorry illogical) but nothing works?

I need solution in Angular or JavaScript not in jQuery.

Thanks.

Answer

Prithivi Raj picture Prithivi Raj · Nov 19, 2017

Try the below subscription to throw alert window on page refresh. do some user events like click over the page before trying to refresh or close the window. check the working version here

see the official documentation on beforeunload

ngOnInit() {
    window.addEventListener("beforeunload", function (e) {
        var confirmationMessage = "\o/";
        console.log("cond");
        e.returnValue = confirmationMessage;     // Gecko, Trident, Chrome 34+
        return confirmationMessage;              // Gecko, WebKit, Chrome <34
    });
}