在鼠标悬停/鼠标移出时更新布尔值

我正在尝试在 mouseover/mouseout 时更新布尔值(它应该动态更改),以便稍后在 if else 语句中使用它并根据 true/false 分配一些函数。但它只显示false而且从不显示true。有人可以帮我吗?


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>

编辑:我需要动态更改布尔值,因为我会将它与其中具有函数的对象一起使用,而我不能从另一个函数调用它们。


牛魔王的故事
浏览 78回答 3
3回答

宝慕林4294392

创建一个函数,例如 MouseHandlerEv,您可以在其中接收布尔值:.HTML文件<div (mouseover)="mouseEvHandler(true)" (mouseout)="mouseEvHandler(false)"></div>.TS文件mouseEvHandler(status){&nbsp; &nbsp;status ? FunctionTrue() : FunctionFalse();}例子:function mouseEvHandler(status){&nbsp; &nbsp;status ? sayHi() : sayBye();}function sayHi() {&nbsp; console.log('HI');}function sayBye() {&nbsp; console.log('Bye');}&nbsp;<div onmouseover="mouseEvHandler(true)" onmouseout="mouseEvHandler(false)">MESSAGE ON CONSOLE</div>将其外推到角度

慕雪6442864

ngOnInit()目前,由于您正在检查钩子中的值,因此仅在组件开始时检查一次值。您可以改为尝试使用 RxJS 使其响应fromEvent并使用它来触发事件。尝试以下模板<div #mouseControl></div>import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';@Component({ ... })export class AppComponent implements AfterViewInit {&nbsp; @ViewChild('mouseControl') mouseControl: ElementRef<any>;&nbsp; ngAfterViewInit() {&nbsp; &nbsp; fromEvent(this.mouseControl.nativeElement, 'mouseover').subscribe(&nbsp; &nbsp; &nbsp; _ => otherFunc();&nbsp; &nbsp; );&nbsp; &nbsp; fromEvent(this.mouseControl.nativeElement, 'mouseout').subscribe(&nbsp; &nbsp; &nbsp; _ => func();&nbsp; &nbsp; );&nbsp; }}

米琪卡哇伊

您可以像下面这样简单地使用它而无需为事件创建函数:<div&nbsp;(mouseover)="mouseEv=true"&nbsp;(mouseout)="mouseEv=false"></div>您还可以尝试将 true 和 false 作为方法参数直接传递给 mouseOver(true) 并在组件中接收其值。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript