Vicheanak
Vicheanak

Reputation: 6684

How to properly add document.addEventListener to Angular2?

I've came across cordova RemoteControl plugin where, to listen to its event, the addEventListener is needed to be registered.

//listen for the event
document.addEventListener("remote-event", function(event) {
//do something
});

Is it a proper way for me to do it?

Upvotes: 4

Views: 25328

Answers (5)

Dipak Delvadiya
Dipak Delvadiya

Reputation: 2112

Try the below step to add event listener using angular 2. I am not sure about "remote-event" event but "click" event is working fine for me as given below.

import { ElementRef, Renderer } from '@angular/core';

constructor(public el: ElementRef, public renderer: Renderer) { 
   renderer.listenGlobal('document', 'click', (event) => {
     // Do something with 'event'
   });
}

Update

As per comment below by @paqogomez.

Renderer has been renamed to Renderer2 and listenGlobal to listen.

Upvotes: 14

erikvimz
erikvimz

Reputation: 5476

I prefer to use @HostListener:

@HostListener('document:remote-event', ['$event'])
onDocumentRemoteEvent(ev: any) {
    // handle the event here
}

Upvotes: 0

Eugene Fedotov
Eugene Fedotov

Reputation: 34

You can use @HostListener it's better solution https://juristr.com/blog/2016/09/ng2-event-registration-document/ If u want to use document.someMethod for angular app also u can inject document in constructor:

import { DOCUMENT } from '@angular/common'; 
@Inject(DOCUMENT) private _document: any

Upvotes: -1

Joe
Joe

Reputation: 871

You can add an EventListener to a constructor

constructor() {
    document.addEventListener("remote-event", function(event) {
       //do something
    },false);
}

Upvotes: 0

Kofi Sammie
Kofi Sammie

Reputation: 3627

this works for me like magic

 document.querySelector('#videostop').addEventListener('click', () => {
            //function here 
            console.log('your result');
         });

Upvotes: 1

Related Questions