How to listen to the mousemove event on a Document object in Angular

I implement drag and drop functions in an angular app: http://jsfiddle.net/Jjgmz/1/

Part of it is listening mousemovefor an event for a document object.

$(document).mousemove(function(e) {});

How can I listen to a document object inside a component?

Let's pretend this is the contents of the component.html file:

<div id="box"></div>

I am using angular 4.

+3
source share
1 answer

1) Using @HostListener( docs ). This is the preferred method, which should be sufficient in most cases.

import {Component, NgModule, HostListener} from '@angular/core'

@Component({
  ...
})
export class MyComponent {
  @HostListener('document:mousemove', ['$event']) 
  onMouseMove(e) {
    console.log(e);
  }
  ..
}

2) (document:event)="handler" DOM, , . , , , .

@Component({
  selector: 'my-app',
  template: `
    <div (document:mousemove)="onMouseMove($event)" id="box"></div>
  `,
})
export class MyComponent {
  onMouseMove(e) {
    console.log(e);
  }
}

3) Renderer (docs) - ; , , , , hook, . , - , ; , , , OnDestroy.

import { Component, Renderer2 } from '@angular/core';

@Component({
  ...
})
export class MyComponent {
  globalListenFunc: Function;

  constructor(private renderer: Renderer2) {}

  ngOnInit() {
    this.globalListenFunc = this.renderer.listen('document', 'mousemove', e => {
      console.log(e);
    });
  }

  ngOnDestroy() {
    // remove listener
    this.globalListenFunc();
  }
}

4) , Angular, , . , .

@Component({
  ...
  host: {
    '(document:mousemove)': 'onMouseMove($event)'
  }
})
export class MyComponent {
  onMouseMove(e) {
    console.log(e);
  }
}

5) , Angular, Observable.fromEvent. RxJS . , , ( async pipe, ). - , .

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import { Subscription } from 'rxjs/Subscription';

@Component({
  ...
})
export class MyComponent {
  subscription: Subscription;

  ngOnInit() {
    this.subscription = 
         Observable.fromEvent(document, 'mousemove')
                           .subscribe(e => {
                             console.log(e);
                           });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

6) , document.addEventListener ; Angular; . DOM , Angular DOM-. Universal SSR.

+13

Source: https://habr.com/ru/post/1656133/


All Articles