Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to know how can I implement a confirm-on-exit component so that on page refresh or leaving tab or window or screen I can execute a confirm on exit method, so that if user click OK he will leave the screen and on click on NO he will remain on same screen?

Code I am using here is:

import { Component, OnInit, Input, Output, HostListener } from '@angular/core';
@Component({
    selector: 'confirmonexit',
    templateUrl: './confirm-on-exit.html' 
})
export class ConfirmOnExitComponent {
    @Input() isDirty: boolean;
    public isConfirmed: boolean = false;
    @HostListener('window:beforeunload',['$event']) beforeUnloadHander() {
        if (this.isDirty) {
            let msg: string = 'Are you sure you want to navigate without saving the entered data on the screen ? '
            if (confirm(msg)) {
                this.isDirty = false;
                this.isConfirmed = false;           
            } else {
                this.isDirty = true;
                event.preventDefault();
            }
        }
    }
}

appModule added - this component in declarations
html added =  <confirmonexit [isDirty]="CreateEditForm.form.dirty"></confirmonexit>

I don't know where the mistake is. I am not able to execute this functionality. Could anyone help me out?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
219 views
Welcome To Ask or Share your Answers For Others

1 Answer

you can use angular deactivate guard on a route .This will execute as soon as you try to navigate away from any route.For example you can refer this https://scotch.io/courses/routing-angular-2-applications/candeactivate

SO if you are using a form then you can pass the form to the guard and then check for form state.if it is dirty it means it has been changed and then you can show the confirm dialog to the user


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...