Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

angularjs directive - how to implement confirm on exit in angular 4?

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...