When user entered some data in form and tried to close browser window accidentally, system has to show alert message to save their data. This example is to implement this functionality using Angular 2.
Source Code       DEMO


Whenever user enter some input, the alert will be activated. Whenever user saves it, alert will be deactivated.  
<input (ngModelChange)="setConfirmUnload(true)" [(ngModel)]="data"/>
<button (click)="saveData()">Save Data</button>

Script - app.component.ts

Observe below functions
import { Component } from '@angular/core';
  selector: 'my-app',
  template: `
  <h4>Enter Text in below Input Field and Try to close Window</h4>
  <input (ngModelChange)="setConfirmUnload(true)" [(ngModel)]="data"/><br>
  <button (click)="saveData()">Save Data</button>
export class AppComponent {
  data: string = '';
  data1: string = '';

    setConfirmUnload(on) {
        window.onbeforeunload = (on) ? this.unloadMessage : null;

    unloadMessage() {
        return "You have unsaved changes";

    saveData() {
        this.data1 = this.data;



  1. I am very happy after visiting your website with very useful information. I am from one of the digital marketing agency... To visit my agency click on link Visitdigitalguru

  2. Write for all sorts of publications whether local or internationals and also try new publications. All will emerge book report helper as your writing skill practices and you will have vast experience.



Popular Posts