BBaysinger
BBaysinger

Reputation: 6987

Angular 2+, how to dynamically bind and unbind to mousemove event

I know how to bind to events using the HostListener decorator like this:

  @HostListener('document:mousemove', ['$event'])
  onMousemove(event) {
    //Some code on mouse movement.
  }

But I would like to be able to bind and unbind to the mousemove event intermittently throughout the lifecycle of a component. I don't know what this type of binding is called, and I can't find anything about it. Should I try to use native JavaScript event binding?

Upvotes: 0

Views: 2037

Answers (2)

Yoav Schniederman
Yoav Schniederman

Reputation: 5391

HTML:

<div (mouseover)="someOverFunction()" 
     (mouseleave)="someLeaveFunction()">
         <span *ngIf="mouseOverDiv == true">hello mouseover</span>
         <span *ngIf="mouseOverDiv == false">hello mouseleave</span>
</div>

TS:

mouseOverDiv : boolean = false;

someOverFunction(){
 this.mouseOverDiv = true;  
}

someLeaveFunction(){
 this.mouseOverDiv = false;  
}

Upvotes: 1

raj m
raj m

Reputation: 2023

Define a output variable like below.

 @Output() mouseEvent = new EventEmitter();

Use this variable when you want to emit the event like below.

 this.mouseEvent.emit({value:paramValue});

Call that mouse event where you want to add in html element

 <HTMLElement (mouseEvent) = "methodName()"></HTMLElement>

Upvotes: 0

Related Questions