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

Markup

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>
<div>{{data1}}</div>

Script - app.component.ts

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

}

0 comments:

Blogroll

Follow this blog by Email

Popular Posts