P
P
plrov2019-12-14 13:06:36
JavaScript
plrov, 2019-12-14 13:06:36

How to block @HostListener listening?

Good day!
There is a component that, using @HostListener, listens for Escape & Enter keystrokes. Somewhere (not in the component code) a MatDialog (dialog box from Angular Material) can be dynamically created. Now the control furrows go to it - and Escape is used to close the dialog box, and Enter to click on the main button of the dialog box.
Question - how to block the @HostListener listener from the component for the duration of the open dialog box?
We considered a variant with a static variable inside the dialog component class, for example, dialogOpened = false, which would become true at the OnInit stage and back false at the OnDestroy stage. However, in this case, setTimeout in OnDestroy is necessary, which, moreover, does not always guarantee that the dialog box has not yet closed at the time of listening in the component.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2019-12-14
@plrov

Not absolutely understood the moment about setTimeout.
In the code of the mat-dialog there is this

// The logic that disposes of the overlay depends on the exit animation completing, however
      // it isn't guaranteed if the parent view is destroyed while it's running. Add a fallback
      // timeout which will clean everything up if the animation hasn't fired within the specified
      // amount of time plus 100ms. We don't need to run this outside the NgZone, because for the
      // vast majority of cases the timeout will have been cleared before it has the chance to fire.
this._closeFallbackTimeout = setTimeout(() => {
        this._overlayRef.dispose();
      }, event.totalTime + 100);

overlayRef.dispose()unbinds from keyboard events.
As I understand it, you want a timeout for the same reason, because Apparently OnDestroy works before unsubscribing, although according to the code it should be after.
The material is quite complicated and I wouldn't rely on it :)
Wouldn't it be easier to make a global service with keyboard events, launch dialog windows with disableClose: true, block service events for all except the dialog when opening the window, and close the dialog itself with hands when receiving an escape event and immediately release the lock?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question