Finding a way to detect the mouse leaving two elements simultaneously in Angular4

Are you looking for the Angular4 equivalent of a particular jQuery functionality? Do you need to add multiple elements dynamically and are experiencing issues with the settimeout function in Angular4? Any thoughts on how to solve this?

http://jsfiddle.net/pFTfm/195/

            var count = 0;
            var tolerance = 500;
            $('#d1, #d2').mouseenter(function(){
                count++;
                $('#d3').show();
            }).mouseleave(function(){
                count--;
                setTimeout(function () {
                    if (!count) {
                    $('#d3').hide();
                    }
                }, tolerance);
            });

in angular

isMouseEnter(e:number){
    this.dropdownId = e;
    this.toogleDropdown = true;

}

hideDropdown(){
    setTimeout(() => {
        if(!this.overElement){
            this.toogleDropdown = false;
        }
        else{
            this.toogleDropdown = true;
        }
    }, 100);

}

Answer №1

Take a look at the live code example here

HTML Code

 <div id="d1" (mouseenter)="mouseEnter('A')" (mouseleave)="mouseLeave('A')">div 1</div>
<div id="d2" (mouseenter)="mouseEnter('B')" (mouseleave)="mouseLeave('B')">div 2</div>
<div id="d3" [ngClass] ="{'hideDiv': div3}">
  div 3
</div>

CSS Styling

   p {
  font-family: Lato;
}
#d1 {
    width: 250px;
    height: 200px;
    background: red;
    display: block;
}

#d2 {
    width: 250px;
    height: 200px;
    background: blue;
    position: absolute;
    top: 150px;
    left: 150px;
    display: block;
}

#d3 {
    position: absolute;
    top: 400px;
    background: green;
    width: 100px;
    height: 100px;
}
.hideDiv {
  display: none;
}

TypeScript Component Logic

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
 div3: boolean = true;
  
  public mouseLeave(type) {
      if(type == 'A' || type == 'B') {
        this.showDiv(true);
      }
  }

  public mouseEnter(flag) {
    if(flag == 'A' || flag == 'B') {
        this.showDiv(false);
      }
  }

  public showDiv(flag) {
    setTimeout(() => {
      this.div3 = flag;
        }, 100);
  }
}

Thank you for checking out the example!

Answer №2

One way to handle this situation is by utilizing the @HostListener method and utilizing the $event.target property to distinguish between the two elements:

@HostListener('mouseleave', ['$event.target'])
onLeave(): void {
  // Utilize the $event.target to distinguish between elements and perform
  // specific actions accordingly.
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Typescript compiler will continue to generate JavaScript code even if there are compilation errors

As a fresh learner of TypeScript, I have been experimenting with some basic concepts. Below is the code from my file app1.ts: class Monster { constructor(name, initialPosition) { this.name = name; this.initialPosition = initialPosition ...

Error in Angular: Trying to access property 'setLng' of a null component variable

Just starting out with Angular and I've come across the error message Cannot read property 'setLng' of null. Can anyone help explain why this is happening? import { Component, OnInit, Input } from '@angular/core'; @Component({ ...

Steps for Subscribing to a Component Event with a Directive

This is a custom Pagination component I have created. <pagination [boundaryLinks]="true" [(ngModel)]="currentPage" [totalItems]="100" previousText="&lsaquo;" nextText="&rsaquo;" first ...

What is the reason behind Angular's repeat filter only being able to access its own element within the return function?

I have successfully implemented some Angular code that is working, however, I am struggling to understand why it works. Coming from a C Sharp background and being new to JS and Typescript. <tr ng-repeat="colleague in Model.FilteredColleagueListModel | ...

The storybook is struggling to find the correct builder for the Angular project

I have set up a complex angular workspace with multiple projects. Within the main angular workspace project directory, I have two folders - one for the project application named eventric, and another for a library called storybook. https://i.stack.imgur.c ...

Unable to access structuredClone on the global object within a Node.js application

structuredClone is causing issues in my NodeJS application. Whenever I try to utilize it, I encounter the error: structuredClone is not defined nodejs. To troubleshoot, I created a simple file and executed the following: console.log({ globals: Object. ...

The Nativescript mobile build can encounter issues if TypeScript file imports do not use correct paths

Whenever I attempt to construct or execute a mobile version of my Angular-built web application using Nativescript, I encounter numerous compiler errors like: src/app/search/search.module.ts(5,29): error TS2307: Cannot find module 'app/common/pipes ...

Adding information to a table using React

I have a collection of nested data that I would like to display in a table using React. Each method is represented in one row, as illustrated in the image. How can I create a row for each method along with its corresponding page names? const methods = [{ ...

Angular 2: The ngOnInit method will be executed after attempting to render the template when initiating from a URL containing an identifier

I'm currently developing an angular application that utilizes the Router to navigate between multiple components starting from AppComponent. In order to demonstrate the issue I am facing, I have created a simplified version on plunker (Interestingly, ...

The error message "indexOf of undefined" appears when trying to read a property that does not exist within a new

Help Needed: The following error is happening: Cannot read property 'indexOf' of undefined at new HttpRequest (http.js:653) at HttpClient.request (http.js:1069) at HttpClient.get (http.js:1157) This occurs when I use the get() method from Ht ...

Angular drag and drop functionality combined with interactive buttons for list management

Looking to create an Angular component for re-sorting objects by dragging from one list to another? I also need this component to include buttons for additional functionality. I've explored the various drag and drop components available on the Angula ...

Managing time in an Angular application using Typescript

I am facing an issue with formatting the time obtained from an API in my FormArray. The time is received in the format: 14.21.00 My goal is to convert this time to the following format: 2:21 PM I have attempted to format it using Angular's DatePip ...

Navigating to a different page rather than a component in Angular

I have a question about routing in Angular. Can I navigate to a page that is within the same component or in a different directory? For example, if we are currently in the component home: home home.component.html home.component.css home.component.ts cl ...

Steps to simulate a TouchEvent programmatically using TypeScript

Is there a way to manually trigger the touch event in TypeScript? In JavaScript, it was possible but I am struggling to achieve the same in TypeScript. For example: let touchStart: TouchEvent = document.createEvent('TouchEvent'); touchStart.i ...

Looking for a solution to resolve the issue "ERROR TypeError: Cannot set property 'id' of undefined"?

Whenever I attempt to call getHistoryData() from the HTML, an error message "ERROR TypeError: Cannot set property 'id' of undefined" appears. export class Data { id : string ; fromTime : any ; toTime : any ; deviceType : string ...

The function will continuously run in a loop when utilized within an HTML template

Currently, I am attempting to dynamically set the color value of an <input type="color"> using a function within the TypeScript (TS) file of the component. Here is how I have implemented it: HTML <input type="color" [value]=&q ...

The expression has been modified following a review with the @ViewChild reference

Hello, I have been working with the context menu component found at https://www.npmjs.com/package/ngx-contextmenu. I encountered an issue when attempting to bind the [contextMenu]="basicMenu" as shown below: @ViewChild(ContextMenuComponent) public basicMe ...

Troubleshooting Angular4 and TypeScript Compile Error TS2453: A Comprehensive

I'm facing an issue in my Angular4 project build process which I find quite perplexing. The error seems to be related to the import of certain components such as Response, Headers, and Http from @angular. Whenever I attempt to build my project, it thr ...

Encountered a problem with NGX Infinite Scroll while implementing it in my Angular project

I'm currently using Angular version 11.0.4 and I've been working on implementing infinite scroll functionality with the help of an npm package. Following all the steps outlined in the documentation at https://www.npmjs.com/package/ngx-virtual-scr ...

Initiating worldwide actions for a "loading" element, like with Angular 1's $emit function

I am currently working on creating a loading overlay component using Angular 2, and I've come to realize that I am unsure about how to trigger it. In Angular 1, I used to emit something and listen in the loading spinner directive to control its visibi ...