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;




Follow this blog by Email

Popular Posts