Angular 2 – communication of typescript functions with external js libraries

Just fire a custom event using dispatchEvent.

In Angular you can listen by adding to any component that is actually added to the DOM:

  • in any template:
<div (window:custom-event)="updateNodes($event)">
  • or in the components class:
@HostListener('window:custom-event', ['$event']) 
updateNodes(event) {
  ...
}
  • or in the @Component() or @Directive() annotation:
@Component({
  selector: '...',
  host: {'(window:custom-event)':'updateNodes($event)'}
})

where custom-event is the type of the dispatched event and updateNodes(event) is a method in your components class.

To manually trigger it in JavaScript:

window.dispatchEvent(new Event('custom-event'));

An alternative approach

would be to make methods of components (or directives, services) available outside Angular like explained in Angular2 – how to call component function from outside the app.

Leave a Comment