zxcwq12
zxcwq12

Reputation: 1

Update boolean value on mouseover/mouseout

I'm trying to update boolean value when mouseover/mouseout (it should change dynamically), to use it later with if else statement and assign some functions based on true/false. But it shows only false and never true. Can someone help me out?

ts:

    mouseEv: boolean;

    mouseOut(e) {
        this.mouseEv = false;
    }

    mouseOver(e) {
        this.mouseEv = true;
    } 

    ngOnInit(): void { 
        if(this.mouseEv == false){ func(); }
        else if(this.mouseEv == true) { otherFunc();};
    }

html:

<div (mouseover)=" mouseOver($event)" (mouseout)="mouseOut($event)"></div>

EDIT: I need to change boolean value dynamically, because I will use it with object that has functions in it and I can't call them from another function.

Upvotes: 0

Views: 2201

Answers (3)

Barremian
Barremian

Reputation: 31125

At the moment, the values are checked only once at beginning of the component since you're checking the values in ngOnInit() hook. You could instead try to make it reactive using RxJS fromEvent and use it to trigger events.

Try the following

Template

<div #mouseControl></div>
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';

@Component({ ... })
export class AppComponent implements AfterViewInit {
  @ViewChild('mouseControl') mouseControl: ElementRef<any>;

  ngAfterViewInit() {
    fromEvent(this.mouseControl.nativeElement, 'mouseover').subscribe(
      _ => otherFunc();
    );

    fromEvent(this.mouseControl.nativeElement, 'mouseout').subscribe(
      _ => func();
    );
  }
}

Upvotes: 0

Adya
Adya

Reputation: 1112

You can simply use it like below without creating a function for event:

<div (mouseover)="mouseEv=true" (mouseout)="mouseEv=false"></div>

You can also try passing true and false directly as method argument in mouseOver(true) and receive its value in component.

Upvotes: 0

Arm144
Arm144

Reputation: 773

Create a function for example MouseHandlerEv in wich you recive the boolean value:

.HTML file

<div (mouseover)="mouseEvHandler(true)" (mouseout)="mouseEvHandler(false)"></div>

.TS file

mouseEvHandler(status){
   status ? FunctionTrue() : FunctionFalse();
}

Example:

function mouseEvHandler(status){
   status ? sayHi() : sayBye();
}

function sayHi() {
  console.log('HI');
}

function sayBye() {
  console.log('Bye');
}
 <div onmouseover="mouseEvHandler(true)" onmouseout="mouseEvHandler(false)">MESSAGE ON CONSOLE</div>

Extrapolate it to angular

Upvotes: 1

Related Questions