Ways to display an icon upon hovering or clicking, then conceal it when the mouse is moved away or another list item is clicked using ngFor in Angular 7

Within a simple loop, I have created a list with multiple rows. When a row is clicked or hovered over, it becomes active. Subsequently, clicking on another row will deactivate the previous one and activate the new one. So far, everything is functioning correctly. However, within each row there are icons that should appear or disappear depending on the row's active state. The icons should show on hover/click and hide when the mouse moves out or another row is clicked. Below is the code snippet:

app.component.html

<ul>
  <li  *ngFor="let row of groups;let i = index" [ngClass]="{'active': clickedIndex == i}" (click)="clickedIndex == i? clickedIndex = null : clickedIndex = i"><span>{{row.items}}</span>---><span>Icon1</span><span>Icon2</span></li>
  </ul>

app.component.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  clickedIndex: number = 0


  groups = [{ "id": 1, "name": "pencils", "items": "red pencil", "Status": [{ "id": 1, "name": "green" }, { "id": 2, "name": "red" }, { "id": 3, "name": "yellow" }], "loc": [{ "id": 1, "name": "loc 1" }, { "id": 2, "name": "loc 2" }, { "id": 3, "name": "loc 3" }] }, { "id": 2, "name": "rubbers", "items": "big rubber", "Status": [{ "name": "green" }, { "name": "red" }], "loc": [{ "name": "loc 2" }, { "name": "loc 3" }] }, { "id": 3, "name": "rubbers1", "items": "big rubber1", "Status": [{ "name": "green" }, { "name": "red" }], "loc": [{ "name": "loc 2" }, { "name": "loc 3" }] }]
}

app.component.css

.active{
background:red;
color:#FFf;
}

Answer №1

To achieve the desired outcome, simply implement the *ngIf directive as shown below (*ngIf="clickedIndex == i") for both icons within spans

<ul>
  <li  *ngFor="let row of groups;let i = index" [ngClass]="{'active': clickedIndex == i}" (click)="clickedIndex == i? clickedIndex : clickedIndex = i"><span>{{row.items}}</span>---><span *ngIf="clickedIndex == i">Icon1</span><span *ngIf="clickedIndex == i">Icon2</span></li>
  </ul>

Here is a functional code snippet for your reference:

https://stackblitz.com/edit/angular-hppkxl?file=src/app/app.component.html

If you wish to show or hide icons upon hover/click events, consider incorporating the mouseenter event along with an additional variable called "hoveredIndex"

<ul>
  <li (mouseenter) ="hoveredIndex == i? hoveredIndex = null : hoveredIndex = i" *ngFor="let row of groups;let i = index" [ngClass]="{'active': clickedIndex == i}" (click)="clickedIndex == i? clickedIndex = null : clickedIndex = i"><span>{{row.items}}</span>--->
  <ng-container><span  *ngIf="hoveredIndex == i || clickedIndex == i">Icon1</span><span *ngIf="hoveredIndex == i || clickedIndex == i">Icon2</span>
  </ng-container>
  </li>
  </ul>

Functional code snippet for your reference:

https://stackblitz.com/edit/angular-ddytef?file=src/app/app.component.html

Answer №2

To achieve the desired effect, you can utilize the mouseenter and mouseleave events. Create a new variable, such as hoveredIndex, and set it to i when the mouseenter event is triggered. Reset it to null on mouseleave. Then, incorporate the necessary conditions in your ngIf.

<ul>
    <li *ngFor="let row of groups;let i = index" 
        [ngClass]="{'active': clickedIndex == i || hoveredIndex === i}" 
        (click)="clickedIndex = i" 
        (mouseenter)="hoveredIndex = i" 
        (mouseleave)="hoveredIndex = null">
        <span>{{row.items}}</span>
        ---><span *ngIf="clickedIndex == i || hoveredIndex === i">Icon1</span>
        <span *ngIf="clickedIndex == i || hoveredIndex === i">Icon2</span>
    </li>
</ul>

An example demonstrating this functionality can be found on StackBlitz.

Answer №3

Avoiding Angular is possible. Simply leverage the pseudo element :hover within your css

Answer №4

If you want to display or hide span icons, you can utilize ng-container in conjunction with *ngIf.

Here's an example:

<ul>
    <li *ngFor="let row of groups; let i = index" [ngClass]="{'active': clickedIndex == i}" (click)="clickedIndex == i ? clickedIndex = null : clickedIndex = i">
        <span>{{row.items}}</span>---> 
        <ng-container *ngIf="clickedIndex == i">
           <span>Icon1</span><span>Icon2</span>
        </ng-container>
  </li>
</ul>

Try it out here!

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

Customize the text color of select list options in Angular 5

Is there a way to style the foreground colors of select list options differently in this dropdown code? <select id="tier" class="form-control" [(ngModel)]="tierId"> <option *ngFor="let m of tierList" value="{{m.tier}}" > {{m.option ...

Unable to delete the margin of Material-ui TextField

Having trouble removing the padding around material-ui's TextField component when using styled-components and inline styling. Any solutions to this issue? Interestingly, the inline width property is functioning correctly, unlike the styled-component w ...

When I employ ngroute, the Angular section in the html page does not display

I am looking to implement a fixed menu named "fixed_admin.html" on my website: <!DOCTYPE html> <!-- saved from url=(0069)https://hackerstribe.com/guide/IT-bootstrap-3.1.1/examples/dashboard/ --> <html lang="en"><head><meta htt ...

Discover the steps for integrating an object into a Ext.grid.Panel using Sencha Ext Js

Currently, I am utilizing Sencha Ext Js 4 and have integrated an Ext.grid.Panel into my project. I am interested in adding another element inside the header, such as a textbox. Is this achievable? {filterable: true, header: 'Unique' /*Here i w ...

send a variable across multiple web pages at the same time

Currently, I have a variable that needs to be passed through multiple PHP pages. The code below effectively sends the variable to one page (index.php). echo "<a href='index.php?PHOTO=".$i."'>select</a>"; However, I am wondering how ...

Steps for dynamically changing the class of a dropdown when an option is selected:

Check out this code snippet : <select class="dd-select" name="UM_Status_Engraving" id="UM_Status_Engraving" onchange="colourFunction(this)"> <option class="dd-select" value="SELECT">SELECT</option> <option class="dd-ok" value= ...

Using the Angular async pipe with an object's property

Is there a way to use the async pipe without ngFor? I need to check a property of an object that is asynchronously loaded with an observable. This is what I have tried, but it's not working as expected: <ion-item *ngIf="user$.anonymouse | async"& ...

The Formly form is experiencing a glitch where it does not reflect the updated default value of

My goal is to dynamically update the Formly form rendering based on changes made in the form scheme (which consists of an array of FormlyFormConfig objects). I have noticed that the updating works when adding a new object or modifying a field label, but it ...

Experiencing issues launching the server.js file on Node.js while incorporating socket.io

Several months ago, I was able to successfully run this code without any issues. However, recently I have encountered some unexpected problems. This code is for a whiteboard app that can be viewed on this link. The current issue I am facing is that when ...

The element 'mat-toolbar' is unrecognized and not known:

Encountering an issue while executing karma tests - the error message indicates that 'mat-toolbar' is not a recognized element within the application. Here are some steps to troubleshoot this problem: 1. Confirm whether 'mat-toolbar' is ...

Hover over with your mouse to open and close the dropdown menu in React JS

Just starting out with React JS and encountering a small issue. I'm trying to make the menu disappear when the mouse leaves that area, so I used onMouseOut and onMouseLeave to close it. However, I noticed that having these options in place prevents th ...

Problem with translating a variable into a selector in JQuery

When attempting to make my Jquery code more flexible, I decided to extract the selector and access it through a variable. However, despite creating variables for both selectors, neither of them seem to be functioning properly. I am confident that the issue ...

Error in Visual Studio with Angular 2 build: 'Promise' name not found

I recently started exploring Angular2 and followed the instructions provided in this quickstart guide: https://angular.io/guide/quickstart Everything seems to be working well after running npm install, but now I want to work on it within Visual Studio usi ...

CSS Element Overlapping Issue in Safari Browser

I am currently developing an audio player for my application that includes a pause/play button, next button, and back button. I have encountered a problem specifically on Safari where the back/pause buttons are overlapping each other. The play/pause button ...

Exploring ways to customize the input color of Material UI TextField when it is disabled [Version: 5.0.8]

I am having trouble changing the border color and text color when an input is disabled. I have tried multiple variations, as seen below: const textFieldStyle = { '& label': { color: darkMode?'#1976d2':'', } ...

Ensure that when you click on the next dropdown menu opener button, the previous dropdown menu closes and only the new menu remains open

Take a look at this page first to get an understanding: On this page, I have implemented multiple dropdown menus that should open when clicked on their respective opener buttons (3 bar icon) and close either when clicked again or anywhere else on the page ...

Is it possible to refresh the page without using a hashtag and stay on the same page in AngularJS

Is it possible to refresh my view from the navigation bar without displaying the server folder? I have the html5Mode activated: if(window.history && window.history.pushState) { $locationProvider.html5Mode(true); } ...

Basic inquiries concerning Vue.js and JavaScript

Hey there, I recently developed a small app to practice my Vue skills. However, there are a few features that I would like to implement but I'm not sure how to do it just yet. <div class="container" id="app"> <div class="row"> <d ...

Unusual Observable behavior in Angular/Typescript leaves developers scratching their heads

I have encountered an issue with a single Angular 2 service: validate() { return this.http.get('api/validate', data); } Consuming the API works fine: this.ValidationService.validate().subscribe(result => { console.log(&a ...

Encountered an issue during my initial AJAX call

Hello everyone, I am currently attempting to use AJAX to send a request with a button trigger and display the response HTML file in a span area. However, I am encountering some issues and need help troubleshooting. Here is my code snippet: //ajax.php < ...