in JavaScript

How to communicate with Angular components outside of Angular

Recently I had to figure out the way to interact with Angular components from outside of Angular, from plain JavaScript rendered to a page. In my case I was opening a modal dialog written in Angular from a traditional server-side rendered page.

I imagine I am not the only one who needs to mix Angular code with other code on the page so I want to share a piece of code that will allow you to do that easily. I based it on a publish-subscribe pattern to separate the code in a nice and clean way.

The basic use-cases are.:

  • To manipulate original webpage from Angular component, without putting DOM manipulation code directly in our component.
  • To call any of our Angular code from the basic <script> tag on the page.

I wrote it as Angular service, named GlobalPubSub. This service has to be part of the Angular module that you load in the page. It will then attach functions on the global window object that you can call outside of Angular.

Basic usage:

  • Inside of your Angular components, subscribe to be notified with globalPubSub.subcribe method and send messages from outside utilizing global window.fireAngularEvent function, passing any number of arguments
  • Outside of Angular, subscribe to be notified with global function window.subscribeToAngularEvent and send messages from Angular by calling globalPubSub.fireEvent

A few notes on implementation:

  • This example is written in TypeScript, but can be rewritten in JavaScript.
  • I decided to have a list of allowed events so that all events have to be defined in the component. This is for better code maintainability, but feel free to use other techniques.
  • To run Angular code from outside Angular, this code has to be called inside so called Angular zone (otherwise strange things would be happening inside your components). This took me some time to figure out!
  • You can rename the methods to make it a bit more general, I wanted to make it clearer when I fire Angular event or event from Angular.
  • The internal, basic implementation of publish-subscribe pattern can be of course rewritten, one of the options would be to use RxJS which you are probably using in your project anyway.

Here it is, let me know what you think!

Write a Comment