Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Basically I have a custom context menu component and I want it to show when a user right clicks in a certain component.

I have implemented the basic functionality, passing the ElementRef to the context menu and adding an custom event handler to handle showing the context menu next to the cursor.

I can see that the event is being fired and the normal browser context menu is not opening due to $event.preventDefault(), but my context menu is not showing up as expected. The boolean should be set so that the *ngIf in the template evaluates to true.

Direct public accessors to the properties have brought me to the same result.

Here is a stackblitz with the implementation

See Question&Answers more detail:os

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...