The problem has to do with the way that the name this
is resolved. At the moment, when your onContextMenu
method is called, this
is not resolved to your AppContextMenuComponent
class (as you might expect). To see this in action, try inserting console.log(this)
somewhere within that method. Since this
is not resolved as you might expect, the assignment statement this._isOpen = true
is not doing what you’d like. One quick fix for this is to explicitly “bind” a value that the name this
should resolve to, by changing your event-listener setup to:
.addEventListener('contextmenu', this.onContextMenu.bind(this));
// ^^^^^^^^^^^
However, this may lead to trouble when you wish to later remove this event listener. Others may have better solutions to this, but one option is to use an arrow function in place of your method (note that this relies on the “class fields proposal”, which is not part of ES6).
Here’s what that change looks like:
private onContextMenu = ($event: MouseEvent): void => {
// ^ ^^
// Body remains unchanged
};
Here’s an updated StackBlitz project with the change.
1
solved Issue with showing a custom context menu