title: Angular2 Custom Events
body: <p>I'm trying to find out how to handle custom DOM events emitted by something outside of Angular, for example the following:</p>
  
  <pre><code>document.querySelector('my-custom-element').dispatchEvent(new Event('my.customEvent'));
  </code></pre>
  
  <p>So far I have tried to register a new EventManagerPlugin that supports everything starting with 'my.' but if I print out all events that come by all 'normal' event like 'click' and 'submit' are printed out; but none of my custom events.</p>
  
  <p>html:</p>
  
  <pre><code>&lt;my-custom-element (my.customEvent)="handleCustomEvent($event)"&gt;&lt;/my-custom-element&gt;
  </code></pre>
  
  <p>ts:</p>
  
  <pre><code>supports(eventName: string):boolean {
      var ret = false;
      if (eventName.indexOf('my.') === 0) {
          ret = true;
      }
      console.log('supports event?', eventName, ret);
      return ret;
  }
  </code></pre>
  
  <p>The console.log line only prints native events and ng*events but not my custom event :(</p>
  
  <p><strong>EDIT Fixed solution</strong>
  I've moved the (my.customEvent) inside the component annd the log showed the custom event.
  Binding an external event to the angular2 internal event while seperating the 2 is fixed by using a custom eventHandler in the EventManagerPlugin
  Relevate code</p>
  
  <pre><code>addEventListener(element: HTMLElement, eventName: string, handler: Function): Function {
      let zone = this.manager.getZone();
  
      // Entering back into angular to trigger changeDetection
      var outsideHandler = (event: any) =&gt; {
          zone.run(() =&gt; handler(event));
      };
  
      // Executed outside of angular so that change detection is not constantly triggered.
      var addAndRemoveHostListenersForOutsideEvents = () =&gt; {
          this.manager.addEventListener(element, 'external.' + eventName, outsideHandler);
      }
      return this.manager.getZone().runOutsideAngular(addAndRemoveHostListenersForOutsideEvents);
  }
  </code></pre>
  
  <p>Trigger the event via DOM:</p>
  
  <pre><code>document.querySelector('my-custom-element').dispatchEvent(new Event('external.my.customEvent'));
  </code></pre>
  
  <p>Now you can trigger an event from the DOM which is pushed into angular2 world and can the code is handled from within the component.</p>