Creating popover windows in Angular

Steve

December 11, 2020

Popovers are great for things like authenticating with a third party without losing the context that your user is in. They’re also pretty simple to implement in Angular.


Create your popover page

The popup is just another browser window, so you can link it to any website (or even route on your own site) that you wish too. In our case, we’re just going to use a very simple HTML page so it loads as fast as possible. But this could also be another Angular application if you were looking for something powerful.


Open it from Angular

In native JavaScript, the window object is used to open popover windows. The API to open windows is very simple, you just have to call window.open with the url you want to use, where to open it and any features you want to apply to the window. Angular has no proxy for this, so we’re going to use the method on the window object directly.


I’m using http-server to serve my popover page which is why the url in the example is http://localhost:8080/. You can also easily do this by running the following command in the same place as your popover page:


npx http-server


Communicating between your application and the window

Like with iframes, we can communicate with the opened window via the built in messaging ability. In our case, the user will be able to enter some text in the opened window. We will then send this message back to our application and close the window.


Then in our application, we can set up an event listener for the messages and react appropriately when it arrives.


Now we’ve got a working popover that can be expanded in many ways!



Minor improvements

Providing window

Using window directly in Angular isn’t great as it makes components a lot harder to test. You can solve this easily by providing window in the module and then importing it via dependency injection.


Better feature handling

Handling the raw string of features can be awkward and prone to errors. What I like to do is define my features in an object, then convert it to a string via JavaScript.


Centering the window

You often don’t want the window stuck in the top left corner of the screen. Luckily it’s simple to center the window on the users screen.


Conclusion

There are many things that are possible with the popover that we’ve now created, like authenticating with third party providers.


Steve

Steve

I'm a Software Engineer on the nerd.vision team. My skills mostly lie in the UI/Node area, but I also work with the backend services.