Move your cursor over a div element while utilizing NgClass

I'm currently working on implementing a hover effect on a div using an Angular ngClass directive. Within the template file, I have a div element with the class "list-item-container" that includes another div with the class "list-item." This "list-item" div is being iterated over using the *ngFor directive. Inside the "list-item" div, there are three child divs with the class "list-item-column," positioned horizontally like a table row with inline display. I've added mouseenter and mouseleave event listeners to the "list-item" div which trigger the hoverListItem() function in my .ts file. The hoverListItem() function toggles the value of the listItemHovered variable between true and false. Additionally, I'm using an ngClass directive on the "list-item" div to apply the 'list-item-highlight' CSS class based on the boolean value of listItemHovered, changing the background color accordingly.

The issue I'm encountering is that when hovering over a specific "list-item" div, all "list-item" divs are being affected rather than just the one I am interacting with. How can I resolve this problem?

.html file

<div class="list-item-container">
    <ng-container *ngFor="let opportunity of dealService.opportunities">
      <div [ngClass]="{'list-item-highlight': listItemHovered}" class="list-item" (mouseenter)="hoverListItem()"
          (mouseleave)="hoverListItem()"
          (click)="selectOpportunity(opportunity)">
        <div
          class="list-item-column">{{opportunity.account?.name === null ? "N/A" : opportunity.account.name}}</div>
        <div class="list-item-column">{{opportunity.requirementTitle}}</div>
        <div class="list-item-column">{{opportunity.salesValue | number: '1.0-2'}}</div>
      </div>
    </ng-container>
  </div>
  

.css file

.list-item-container{
    overflow: auto;
    width: 100%;
    max-height: 500px;
  }
  
  .list-item{
    font-size: 15px;
    border-radius: 10px ;
    margin-top: 5px;
    height: 50px;
    background: lightgray;
    color: black;
  }
  
  .list-item-highlight{
    background: #7e00cc;
    color: white;
  }
  
  .list-item-column{
    height: inherit;
    vertical-align: center;
    display: inline-block;
    width: 33.33%;
    padding-left: 40px;
  }
  

.ts file

 hoverListItem() {
      this.listItemHovered = !this.listItemHovered;
    }
  

Answer №1

Currently, you are managing the listItemHovered flag within the component context, but it would be more efficient to maintain a separate flag for each item level. This approach will make it easier to determine whether the component has been highlighted or not.

[ngClass]="{'list-item-highlight': opportunity.listItemHovered}"
(mouseenter)="hoverListItem(opportunity)"
(mouseleave)="hoverListItem(opportunity)"

Component

hoverListItem(opportunity) {
   opportunity.listItemHovered = !opportunity.listItemHovered;
}

If the sole purpose is to highlight the element on hover, I suggest using the :hover pseudo-class. By modifying the CSS rule, this can be achieved without requiring multiple change detection cycles.

.list-item:hover {
  background: #7e00cc;
  color: white;
}

Answer №2

To enhance the user experience, one approach is to implement a directive that captures the hover event on the specified element and adds the necessary class:

@Directive({
    selector: '[hoverDir]'
})


 export class HoverOverDirective { 
    @HostListener('mouseenter') onMouseEnter() {
       this.elementRef.nativeElement.class = 'list-item-highlight';
    }

     @HostListener('mouseleave') onMouseLeave() {
       this.elementRef.nativeElement.class = 'list-item-not-highlight';
     }
}

Alternatively, you can utilize the built-in functionality of CSS pseudo property :hover by incorporating it like so:

.list-item:hover {
  background: #7e00cc;
  color: white;
}  

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

Updating div visibility based on form content in PHP

I am struggling to find a way to filter a page filled with divs based on form input to determine whether they should be displayed or not. The layout is akin to a collection of articles, where each div showcases an image and some text that links to the comp ...

Tips for executing several HTTP requests from an array using RXJS

At the moment, I am working on a synchronization service using Angular. My goal is to make a database request and receive an array of URLs in return. The next step is to process each URL sequentially. Below is the current code: return this.http.get<any ...

Outputting HTML from a function

As a beginner, I have a question about best practices. Is it more effective to return HTML from a function like the following: function displayHtml($userName) { $htmlMsg = " <html> <head> <title>Displaying HTML</title&g ...

Utilize the power of Angular 12 and Bootstrap 5 with the ability to load multiple imported scss theme files

I'm currently incorporating Angular 12 and Bootstrap 5 into my project. For loading Bootstrap, I have imported it from my SCSS file along with three theme SCSS files. This is how it appears: style.scss: @import './assets/styles/theme1.scss&apo ...

Struggling to find a solution for altering font color with jQuery while creating a straightforward menu

I'm having trouble changing the color of the active button pressed to "color:white;"... Here is the link to the jsfiddle: http://jsfiddle.net/wLXBR/ Apologies for the clutter in the file, my css is located at the bottom of the CSS box (Foundation cod ...

adjust the size of the textarea to perfectly fill the available space

I want my textarea within the wrapctxt container to always fill up the remaining space below the wrapctop section, reaching the bottom of the wrapc element. .panelb{ display:grid; grid-template-columns: 130px 34% auto; height:100vh; width: ...

Resize the tab header in primefaces to fit your needs

Is there a way to change the height of the tabView's header specifically in primefaces? Take for instance the tabs with headers like "God Father I", "God Father II" on this link, I only want to adjust the height of the header and not the entire tab. ...

having difficulty applying border color to input when clicked

Is there a way to change the border color of an input field on an onClick event? In my scenario, if the 'Other' radio button is selected and a user attempts to save without entering any value in the input field, I want the border color of the in ...

LFT Etica font showcases digits with varying heights

In the project I am working on, we are required to use the font LFT Etica. However, there is an issue with the height of certain digits when displayed. Specifically, some numbers appear taller than others. Is there a way to make all digits have equal heigh ...

What is the best way to symbolize a breadcrumb offspring?

In my table representation, the breadcrumb is shown as: <ol class="breadcrumb" data-sly-use.breadcrumb="myModel.js"> <output data-sly-unwrap data-sly-list="${breadcrumb}"> <li itemscope itemtype="http://data-vocabulary.org/ ...

Updating hyperlinks from dynamic php links to stable static links

I have a script that predominantly uses absolute addressing, but now I need to switch to relative addressing. The problem I'm encountering is when trying to change the links in PHP from: <link href="<?php print $theme; ?>style.css" type="tex ...

Enhance your React project by incorporating Material-UI card media elements with the ability to add

I am trying to figure out how to create an opaque colored overlay on top of an image using Material-UI. While it is possible with plain HTML, CSS, and JavaScript, I am facing some challenges with Material-UI. <Card> <CardMedia> <im ...

Tips for transferring information from a form to your email address

I am trying to find a way to automatically send form data to my email without the user having to open their inbox. I attempted to use the "mailto" function but it didn't work as desired, still opening the email box. Here is the script I tried: functio ...

Retrieve a specific value from the NGXS state by providing a parameter

I have a unique situation where my state contains JSON data like this: {id: "1", name: "ig1", description: "ig 11"} {id: "5", name: "hhh", description: "hhh"} {id: "6", name: "ggg", description: "hhh"} My goal is to specifically extract the data for id = ...

Capture various data points in an array with each click

I am currently working on a menu of buttons where users can select multiple options at the same time. My goal is to record all selected buttons in one array instead of individual arrays for each button. The end result I hope to achieve is an array like t ...

What factors dictate the color of rows in jquery datatable designs?

Within the jQuery datatable styles, such as "smoothness," the rows are displayed in different colors. What factors determine which colors are shown on each row? And is there a way to customize this color scheme? Refer to the example below from their sampl ...

How to Create a Floating DIV with CSS

Here is the URL I am referring to: Website I want to position the Weather DIV above other content on the page while still maintaining its position when expanded or collapsed. How can I achieve this without affecting the layout of other elements? This is ...

Go to a different page section using MUI 5

I am currently working on a React application and I want to implement a functionality where pressing a button on my Nav Bar will navigate to a specific section on the first page. To achieve this, I have created an onClick function for my button: const onNa ...

Looking for assistance with transforming my Angular 2 component into an npm package

After successfully creating a component in Angular 2, my next step is to convert it into an npm library for easy installation. npm install Despite installing Angular CLI and searching online, I have been unable to find clear instructions on how to effe ...

Is it possible to extract only the Bolded Text and store it in a String Array within a Spanned String

I need help with extracting bolded text from my paragraph-long stories that are saved as spanned strings in an EditText. The regular text is interspersed with a few bolded words here and there, and I want to be able to search through the spanned string a ...