0

Trying to get a message for user before he click back button from the browser and go out from the app. in my app user cant go back unless he use the buttons inside the app. so i want to pop up some message when the user use back button from the browser.

i managed to get event of the click back button but cant get a pop up to pops after.

window.onpopstate = function (e) {

  this.dialog.open(PopupComponent, {
    data: {
      data: optionsBox,
      hint: 'test',
    }
  });
}

getting error: Property 'dialog' does not exist on type 'WindowEventHandlers'.ts(2339)

Roberto
  • 187
  • 3
  • 15
  • what is this.dialog in this case? – Andrei Mar 28 '19 at 15:29
  • 1
    You need to use an arrow function to make this work. But I strongly recommend to use another approach to detect the back button inside an Angular app. – JSON Derulo Mar 28 '19 at 15:35
  • @JSONDerulo it works, can u explain why? – Roberto Mar 28 '19 at 15:38
  • Because a normal function creates a new context, while an arrow function preserves the context. As your service is bound to the context of your component, it is not available inside a normal function. – JSON Derulo Mar 28 '19 at 15:39
  • Further reading: https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-exchangeable – JSON Derulo Mar 28 '19 at 15:40

1 Answers1

0

This happens because a JavaScript function creates a new context, where your dialog service is not available. To avoid this behavior, you need to use an arrow function which preserves the current context.

window.onpopstate = (e) => {
  this.dialog.open(...);
}
JSON Derulo
  • 9,780
  • 7
  • 39
  • 56