import { Inject , Injectable } from '@angular/core' ; import { ControlContainer } from '@angular/forms' ; import { TranslateService } from '@ngx-translate/core' ; import { ObPopUpService } from '../pop-up/pop-up.service' ; import { WINDOW } from '../utilities' ; import { Window } from '@popperjs/core' ; @ Injectable ( { providedIn : 'root' } ) export class ObUnsavedChangesService { public isActive = true ; private readonly controlContainer : { [ key ] : ControlContainer ; } = { } ; constructor ( private readonly translateService , private readonly popUpService , @ Inject ( WINDOW ) window ) { window . addEventListener ( 'beforeunload' , e => this . onUnload ( e ) ) ; window . addEventListener ( 'unload' , e => this . onUnload ( e ) ) ; } watch ( formId , form ) { this . controlContainer [ formId ] = form ; } unWatch ( formId ) { delete this . controlContainer [ formId ] ; } canDeactivate ( ) { return this . ignoreChanges ( ) ; } ignoreChanges ( formIds ? ) { return this . hasPendingChanges ( formIds ) ? this . popUpService . confirm ( this . message ( ) ) : true ; } private onUnload ( event ) { if ( this . hasPendingChanges ( ) ) { const confirmationMessage = this . message ( ) ; event . returnValue = confirmationMessage ; return confirmationMessage ; } return null ; } private hasPendingChanges ( ids = Object . keys ( this . controlContainer ) ) { const includesPendingChanges = Object . keys ( this . controlContainer ) . filter ( formId => ids . includes ( formId ) && this . controlContainer [ formId ] . dirty ) . length > 0 ; return this . isActive && includesPendingChanges ; } private message ( ) { return this . translateService . instant ( 'i18n.validation.unsavedChanges' ) ; } }