Angular 2 - communication of typescript functions with external js libraries

前端 未结 1 1272
忘掉有多难
忘掉有多难 2020-11-27 19:02

Using Javascript Infovis Toolkit as an external library for drawing graph and trees. I need to manipulate the onClick method of nodes in order to asynchronously sending an H

相关标签:
1条回答
  • 2020-11-27 20:00

    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.

    0 讨论(0)
提交回复
热议问题