Display the assigned image when hovering over each item in the list

I am currently working on a project to showcase a list of names along with their corresponding images.

To achieve this, I have set up a service that includes all the names and associated images:

import { Case } from './case';

export const CASES: Case[] = [
  { name: 'Diesel', image: '/assets/images/diesel.png', link: '' },
  { name: 'WeWork Berlin', image: '/assets/images/berlin.png', link: '' },
  { name: 'Fritzhansen', image: '/assets/images/fritzhansen.png', link: '' },
  { name: 'Savum', image: '/assets/images/savum.png', link: '' },
  { name: 'Eskay', image: '/assets/images/eskay.png', link: '' },
  { name: 'Diesel', image: '/assets/images/diesel-snd.png', link: '' },
  { name: 'Mobilia', image: '/assets/images/mobilia.png', link: '' },
  { name: 'Rarekind', image: '/assets/images/rarekind.png', link: '' }
];


The list of cases is retrieved in the case-list component.ts file:

import {Component, OnInit} from '@angular/core';
import { CASES } from '../mock/mock-cases';

@Component({
  selector: 'app-case-list',
  templateUrl: './case-list.component.html',
  styleUrls: ['./case-list.component.scss']
})
export class CaseListComponent implements OnInit {

  cases = CASES;

  ...

}


In the case-list's HTML file, I am using a loop to display the names and their images:

<div *ngFor="let case of cases" class="container-fluid d-flex justify-content-center">

  <ul>
    <li class="text-center">
      {{ case.name }}
    </li>
  </ul>

  <img src="{{ case.image }}" alt="First" class="position-absolute align-self-center d-none">

</div>


However, I want to enhance this functionality. Currently, all images are visible at once.

My goal is to make the image appear only when the corresponding li item is hovered over. Moreover, I want only the image linked to the hovered li item to be displayed - for example, if the "Savum" item is hovered over, only its image 'savum.png' should show.

How can I implement this feature in Angular?

Answer №1

Create two functions for mouseenter and mouseleave events, allowing the image url to be set when hovering over a specific list item. The mouseenter function retrieves the url of the item as a parameter and stores it in a public property called imageUrl.

Here is an example of what your .ts file should look like:

    export class CaseListComponent implements OnInit {

      cases = CASES;

      imageUrl: string;

      mouseEnter(url: string) {
        this.imageUrl = url;
      }

      mouseLeave() {
        this.imageUrl = null;
      }

    }

// Use the stored imageUrl value to update the src attribute of the image tag, displaying it if there's a string present. Validation is omitted for simplicity.

Your .html code would be structured similarly to this:

<div class="container-fluid d-flex justify-content-center">

  <ul>
    <li (mouseenter)="mouseEnter(case.image)" (mouseleave)="mouseLeave()" class="text-center" *ngFor="let case of cases">
      {{ case.name }}
    </li>
  </ul>

  <img *ngIf="!!imageUrl" [src]="imageUrl" class="position-absolute align-self-center">

</div>

Answer №2

Here is my proposed solution:

  1. Add a unique css class to each li and img based on their index. Initially hide each image.

  2. Implement the mouseenter and mouseleave events for each li element as shown below:

      <ul>
        <li class="text-center" *ngFor="let case of cases, let i=index" 
            (mouseenter)="mouseEnter(i)"  
            (mouseleave)="mouseLeave(i)">
          {{ case.name }}
        </li>
      </ul>
    
      <img *ngFor="let case of cases, let i=index" src="{{ case.image }}" alt="First" class="position-absolute align-self-center icon-image" ngClass="imgss{{i}}">
    </div>
    

The css rule for .icon-image class should be as follows:

  .icon-image{
  display: none;
}
  1. In your TypeScript file, handle the events and modify the visibility of the elements based on the hovered index.

`

mouseEnter(itemIndex){
 console.log('hover over', itemIndex);
 const element = this.elRef.nativeElement.querySelector(`.imgss${itemIndex}`);
 element.style.display ="block";
 console.log('hover over', element);
}
mouseLeave(itemIndex){
 const element = this.elRef.nativeElement.querySelector(`.imgss${itemIndex}`);
 element.style.display ="none";
}

` View a working example here:

Working demo

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

Each element in ngFor triggers the invocation of ngAfterContentInit by Angular

In my Angular 11 (Ionic 5) app, I have a scenario with two components: A ContainerComponent and a BoxComponent. Both of these components are completely transparent (template: '<ng-content></ng-content>'). The challenge is for the cont ...

What's the best way to handle variables and numerical calculations within PHP loops when dealing with forms?

I'm currently developing a basic PHP page where users can choose how many numbers they want to add together. After selecting the quantity, they input the numbers on a new page, click a button, and then see the sum displayed. The challenge I'm fa ...

Adaptable CSS triangle design

Hello I'm looking to create a responsive CSS triangle similar to the image linked below. I attempted using percentages with border width, but didn't achieve the desired outcome. Can anyone suggest a simple solution? https://i.stack.imgur.com/Yah ...

Struggling to properly position navigation bar items in a Bootstrap website

I'm struggling to align the bar items on a new site that I've built. I've tried placing two bars at the top to mimic the layout of this site: . I'd like it to look similar to this site: , where everything is nicely centered and mobile-f ...

Managing the subscription function within the change event of a select tag in Angular 5 to prevent it from triggering repeatedly

Here is my DataService.ts: export class DataService { dataObs$: any; constructor(private http: HttpClient) { } getUsers() { return this.http.get('https://jsonplaceholder.typicode.com/users'); } getPostsById(id: number, refresh: boolean = ...

Changing the color of the selected item in a Jquery Mobile ListView

I have a dynamic list that triggers a JavaScript function using the onclick event. However, I am struggling to change the color of the selected item in the list. Here is an example of the code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional ...

Exploring alternative methods for accessing object values in TypeScript using a string object path without relying on the eval function

If we have an object in JS/typescript structured like this: var obj = { a: { b:{ c:1 } } } And a string "b.c" is given, how can we evaluate this using only the variables provided and retrieve the value 1 from the object without rel ...

The top-center alignment in Toaster (ngx-toastr) is missing a top margin

I recently started using the ngx-toastr library in my project. I have a message service that displays error messages at the top-center of the screen with the following code: @Injectable() export class MessageService { constructor(private toastrServic ...

Issue with TypeScript createProgram due to undefined 'ts.sys' error

I am encountering an issue while trying to utilize the createProgram function. The error message states that ts.sys is undefined when running the following code: try { createProgram(Utils.getFileNames(), { lib: ['lib.es6.d.ts'] ...

"Troubleshooting vertical tab inconsistencies in Jquery: addressing unexpected gaps and alignment

After spending a considerable amount of time on this, I'm still struggling to make it work properly. The main issue is the gap between the tabs and the content area. I've tried adjusting the positioning, but it ends up affecting the overall layo ...

How wide should a <NavDropdown> be in react-bootstrap 5?

Another day, another challenge. CSS is not my forte, oh dear. I'm attempting to adjust the width of a dropdown in react-bootstrap. Here's what I tried: <NavDropdown style={{width: "5vw"}} title="User" id="navbarScroll ...

What is the best way to host a single page application within a sub-directory using nginx?

Trying to set up nginx to host an Angular application from a unique child path. Adjusted the app to use a base href of fish, able to serve root page and assets correctly. However, encountering a 404 error when attempting to reload the page on a child rout ...

Typescript integration in Next.js

When deploying a Next.js project with TypeScript, sometimes errors occur that do not show up during development. Here is an example of such an error: 13:09:26 Failed to compile. 13:09:26 ./node_modules/next/dist/build/webpack/plugins/pages-manifest ...

Exploring the world of video playback with Angular

I'm currently developing an Angular application and incorporating the HTML 5 video tag in my code to enable video playback. The relevant code snippet is as shown below: <video autoplay> <source src="videos/video.mp4" type="video/m ...

What is the best way to automatically scroll to the chosen option when a button is clicked?

Is there a way to make the select box automatically scroll and show the selected option when the focus button is clicked? The current method I am using with focus does not achieve this. Are there any JavaScript or jQuery methods that can help me solve th ...

Is there a way for me to determine the exact coordinates of all buttons on a given webpage?

I came across this piece of code, but I'm a bit unsure about where exactly I should input it and how to adjust it to locate the position of each button. Additionally, I'm curious as to where the results (coordinates) will be shown? function find ...

How can I delete an individual HTML element that does not have a class or ID?

I am currently working with a theme that cannot be altered due to automatic update requirements. The theme includes the following HTML code snippet: <div class="dropdown-menu"> <a href="#">Profile</a> | <a href="#">Logout</a> ...

Modifying css background in real-time based on the current weather conditions

Is there a way to dynamically change the background image in CSS based on the weather condition? I'm utilizing the wunderground API to retrieve the weather data, which is stored in the weather variable. I am struggling with how to update the backgrou ...

Can you tell me about the feature called "Inspect Browser" box?

Can you identify the significance of this enigmatic purple box while inspecting elements in the browser's developer tools? It does not correspond to padding, margins, or borders, yet it seems to be occupying space within the designated div. [1]: http ...

The primary section is not extending completely to the bottom, resulting in the footer not being aligned correctly at the bottom of the

Despite the numerous similar questions on Stack Overflow, I am struggling to get my footer positioned correctly on my page. The <footer> stubbornly remains 800px above the bottom behind the <main>. Even with various height options such as 100%, ...