Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

angular - Issue with showing a custom context menu

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...