Choose a specific div element from a collection of dynamically generated divs in Angular

I have been working on a code to dynamically generate div elements using the *ngFor directive. Here is what I have so far:

<div *ngFor = "let item of Items">
<p>Item : {{item}} </p>
</div>
    

The challenge I encountered is that when I hover over a specific div, I want only that particular div to be highlighted with a background color.

If I use the mouseenter attribute on the div tag, it highlights all the div elements instead of just the one I hovered over.

<div (mouseenter)="hovered=true" 
           (mouseleave)="hovered=false" 
           *ngFor="let item of Items"  
           [style.background]="hovered? 'red' : none">
        <p>Item: {{item}}</p>
    </div>
    

Does anyone know how to achieve this?

Answer №1

I'm curious about how your *ngFor directive works because you're using let item in Items instead of let item of Items (it should be of, not in).

app.component.html

<div *ngFor = "let item of Items">
  <p> Item: {{item}}  </p>
</div>

app.component.css

div:hover{
  background-color: yellow;
}

Check out the working Stackblitz here.

Edit:

In response to your updated question, you are applying hover styles to all elements instead of each individual element. To achieve this, you can use the following approach:

<div (mouseenter)="hover=i" (mouseleave)="hover=-1" *ngFor = "let item of Items;let i = index"
       [style.background]="hover=== i ? 'red' : none">
  <p> Item: {{item}}  </p>
</div>

Now you can achieve the desired behavior without using CSS, and see a working example by clicking on the link below.

View the edited Stackblitz here.

Answer №2

Utilize the CSS :hover pseudo-class to create hover effects on elements.

html

<div *ngFor="let item of items">
  <p class="hover-target">Item : {{item}} </p>
  <p>footer</p>
</div>

css

.hover-target:hover {
  background-color: red;
  /* add any styles you want to apply */
}

Note - Be cautious of your *ngFor syntax. It should be *ngFor="let item of Items"

DEMO: https://stackblitz.com/edit/angular-kp4zfv

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

Unable to locate a resolution for the error message "Warning: Task "uglify" not found"

Below is the content of my Gruntfile.js: module.exports = function(grunt) { require('load-grunt-tasks')(grunt); grunt.initConfig({ uglify: { start: { files: { 'js/script.min.js': ['js/script.js&a ...

Header escapes div and continues to move

I am currently working on building a website. One of the key features I want to include is a fixed top bar that remains visible at all times. In this bar, I have added buttons, an image, and a headline. However, I am facing an issue where the headline keep ...

Unable to retrieve content in NGX-Quill upon submission

I am currently using "ngx-quill": "^14.3.0" along with "@angular/core": "~12.2.0". It is registered in the app module: QuillModule (not for root). And also in the lazy loaded module: QuillModule (not for root). public editor = { toolbar: [ ...

Using Inheritance to Create Custom Event/Callback Handlers in TypeScript

Currently facing an issue with Typescript that I'm stuck on. I have created a named callback Handler class that receives the allowed list of "events"/"handlernames" as a generic: class NamedHandler<H extends { [key: string]: HandlerFunction }> ...

Adjusting the height of a Vue component to 100% triggers a change in height whenever a re-render occurs

In my Vue component, there is a class called "tab-body-wrapper" that serves the purpose of displaying the "slot" for the active tab. However, I encountered an issue while troubleshooting where the height of the ".tab-body-wrapper" component reduces during ...

Having trouble with refreshing the div content when using jQuery's $.ajax() function

My goal is to refresh a div that has the id #todos after saving data in the database. I attempted to use .load() within $.ajax() $('.todo--checkbox').change(function () { let value = $(this).data('value'); $.ajax({ url: ...

Failed to add a new entry to the Sharepoint 2013 List

Having trouble saving an item to a SharePoint list using Knockout.js and REST. In my Ajax POST request, I've used ko.toJSON but the entry doesn't show up in the SharePoint list. It's possible that I'm passing the wrong parameter value. ...

Break down the organization of CSS

While exploring a website, I came across this CSS code that sets the font family to "Open Sans," Helvetica, Arial, and sans-serif. However, I am having trouble understanding this structure. Any assistance would be greatly appreciated. Thank you in advanc ...

Troubleshooting: Why the TableTools basic usage example is not functioning as

After replicating the code from http://datatables.net/release-datatables/extensions/TableTools/examples/simple.html in my Visual Studio project, I organized the files by saving two css files as style1.css and style2.css, along with three js files named sc ...

Helping React and MUI components become mobile responsive - Seeking guidance to make it happen

My React component uses Material-UI (MUI) and I'm working on making it mobile responsive. Here's how it looks currently: https://i.sstatic.net/kxsSD.png But this is the look I want to achieve: https://i.sstatic.net/kJC2m.png Below is the code ...

Can the <container> block be positioned beneath the <header> block?

header { background: blue; color: white; width: 100%; } .container { background: green; text-align: center; width: 100%; height: 100px; transform: skew(0, -10deg); color: white; position: relative; top: 55px; } .container .home{ p ...

To prevent the background image (blue border) from shifting, I need to extract the list item element without causing the image to

Having trouble with the side borders on my navbar. I've used a background image for the border (blue line) in the list item of the navbar. Is there a way to move down two specific list items slightly, like shown in my screenshot? I need to bring down ...

Angular: Automatically close the side navigation menu when a user clicks anywhere outside of it in the screen

My current issue involves using a sidenav library where I need to close the sidenav when the user clicks anywhere on the screen. Despite several attempts, I have been unable to make it work successfully. Below is the code snippet in question: html < ...

Dynamic TypeScript property that can only be assigned values from an array during runtime

I'm currently struggling with specifying allowed values for a property in TypeScript. Within my interface, I have statically typed the property like this: interface SomeInterface{ prop: "bell" | "edit" | "log-out" } However, I am looking for a w ...

Unable to render a stationary image located within the component's folder in Angular

Within the components directory, I have placed an image file. It's a simple PNG with a logo on it. The four files in the directory are: blobb.png blobb.comp.ts blobb.comp.html blobb.comp.scss In the HTML file, I included the image using a static so ...

Tips for integrating TypeScript with Vue.js and Single File Components

After extensive searching online, I have struggled to find a straightforward and up-to-date example of setting up Vue.js with TypeScript. The typical tutorials out there either are outdated or rely on specific configurations that don't apply universal ...

Is it possible to remove a particular div after clicking the delete button, especially if multiple divs are displayed upon clicking the add

var count = 2; var countMax = 5; function adddt() { if (count > countMax) return; document.getElementById('dt-' + count + '').style.display = 'block'; count++; } <link href="https://maxcdn.bootstrapcdn.com/bo ...

When using Typescript, the keyof operator for objects may not undergo refinement and can result in error

I've been working on creating a function that validates whether a key in an object is a non-empty string. export const validateRequiredString = <T>( obj: T, key: keyof T & (string | number) ): void => { if (typeof obj[key] !== " ...

"Apply a class to a span element using the onClick event handler in JavaScript

After tirelessly searching for a solution, I came across some answers that didn't quite fit my needs. I have multiple <span id="same-id-for-all-spans"></span> elements, each containing an <img> element. Now, I want to create a print ...

Creating a Full Page Background Image That Fits Perfectly Without Resizing or Cropping

Can someone help me achieve the same effect as the website linked below, where the background image fades instead of being a slideshow? The image should be 100% in width and height without any cropping. I have managed to set this up with the codes provided ...