With the new release of the Angular CDK (v7.3.0), the overlay position strategy gets a new cool ability that we can use to help us create context menus with ease.

The positioning strategy now allows for the connected overlay’s origin to be set to a point on the page, rather than a DOM element. This enables implementing right-click context menus easily.

Let’s examine the new functionality by creating a Gmail-style list:

We create a users’ list, and attach a contextmenu event, that invokes the open() method, passing it the event object and the current user whenever the user right-clicks on a div.

We also create the context menu by using ng-template . Later, we’ll see how we can inject it into the overlay.

Let’s continue with the component:

The open() method gets the x and y coordinates from the event object and passes them to the flexibleConnectTo() method. We also set the scrollStrategy to close() to get the same behavior as in Gmail — close the menu when the user scrolls the page

The last step is to attach the overlay to the page with the provided TemplateRef , which we obtained by using ViewChild . We also pass the context , which consists of the current user object that we got as the second parameter.

If you’re unfamiliar with the Overlay feature, I recommend reading this article I wrote on the subject:

Let’s finish by adding the behavior of closing the menu when clicking outside it:

On each click, we check if the current target is NOT the overlay element or contained within it, and if that’s the case, we close the menu.

🔥 Last but Not Least, Have you Heard of Akita?

Akita is a state management pattern that we’ve developed here in Datorama. It’s been successfully used in a big data production environment, and we’re continually adding features to it.

Akita encourages simplicity. It saves you the hassle of creating boilerplate code and offers powerful tools with a moderate learning curve, suitable for both experienced and inexperienced developers alike.

I highly recommend checking it out.

Follow me on Medium or Twitter to read more about Angular, Akita and JS!