Events for individual items in Angular using ngFor

TypeScript:

displayText: boolean = false;

  showOnHover(){
    this.displayText = true
  }

  hideOnLeave(){
    this.displayText = false;
  }

Html

<ul> 
<li class="txt-block"
    *ngFor='let element of elementsToDisplay;let i = index'>
  <div class="form-control">
      <input type='text' (mouseenter)="showOnHover()" (mouseleave)="hideOnLeave()" id = 'elmt'+i name='element'/>
      <span *ngIf = 'displayText'> {{element}} </span>
    </li>
 </ul>

This code dynamically creates textboxes using ngFor. When a mouse enters a textbox, the corresponding Span element should be displayed.

However, currently when hovering over a specific text box, all Span elements are being shown. Assistance in resolving this issue would be greatly appreciated.

Answer №1

If you're looking for a simpler solution, CSS can actually help achieve this. It eliminates the need to constantly manage the hover state in your TypeScript code, allowing you to remove the (mouseenter) and (mouseleave) bindings.

To start off, set the initial display of the element to none:

input + span {
  display: none;
}

When the input is hovered over, the span will be displayed:

input:hover + span {
  display: inline-block;
}

Consider giving the span a more meaningful class name instead of using just "span" in the CSS rule, but that decision is ultimately up to you.

Check out the live demo on StackBlitz

Answer №2

To display text, you must use an index with showText

 showText: any = [];

  toggleHoverState(index){
    this.showText[index] = !this.showText[index];
  }

<ul> 
<li class="txt-block"
    *ngFor='let item of itemsToDisplay; let i = index'>
  <div class="form-control">
      <input type='text' (mouseenter)="toggleHoverState(i)" (mouseleave)="toggleHoverState(i)" id='itm'+i name='item'/>
      <span *ngIf='showText[i]'> {{item}} </span>
    </li>
 </ul>

Check out the code on stackblitz here

Answer №3

The issue arises from the lack of connection between your mouseenter function and the specific span element that needs to be displayed. This should ideally be a one-to-one relationship, but in your current setup, it seems to be a one-to-many relationship. To rectify this problem, consider adjusting your code as follows:

showText: Array<boolean> = this.fruitsToDisplay.map(value => false);

  hoverStateIn(index){
    this.showText[index] = true
  }

  hoverStateOut(index){
    this.showText[index] = false;
  }
<ul>
<li class="txt-block"
    *ngFor='let fruit of fruitsToDisplay; let i = index'>
  <div class="form-control">
      <input type='text' (mouseenter)="hoverStateIn(i)" (mouseleave)="hoverStateOut(i)" id='frt'+i name='fruit'/>
      <span *ngIf='showText[i]'> {{fruit}} </span>
    </li>
 </ul>

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

Passing an array of ID's between two components in Angular: A comprehensive guide

Greetings fellow readers, I have encountered a new challenge in my Angular project. I need to pass an array of IDs from one component to a completely unrelated component. Most solutions suggest using ViewChild, Input, or Output, but since the components ar ...

What is the best way to save values from an input field to a temporary array and then showcase them in a list using Angular 2?

One of the challenges I'm facing is incorporating an input field into my form. This input field is specifically for capturing contact numbers. Users should have the ability to add multiple contact numbers without the need for separate fields. Hence, ...

Execute an npm script using a gulp task

Is there a way to execute an npm script command within a gulp task? package.json "scripts": { "tsc": "tsc -w" } gulpfile.js gulp.task('compile:app', function(){ return gulp.src('src/**/*.ts') .pipe(/*execute npm run tsc*/ ...

Ways to prevent the jQuery simple slider from transitioning slides while it is in an invisible state

There is a jQuery slider on my website that behaves strangely when I navigate away from the Chrome browser and return later. It seems to speed through all pending slides quickly when it was not visible. Now, I want the slider to pause when it becomes invi ...

Stopping an ongoing API service call when an Angular route changes can be achieved by following these steps

Within my application, there are various pages accessible through the dashboard. When loading the dashboard page, multiple API services are called to retrieve reports. However, if a user clicks on a different page link while the dashboard is still loading, ...

Using Jasmine to Jest: Mocking Nested function calls

I am currently working on testing my TypeScript functions with Jasmine: //AB.ts export async function A() { } export async function B() { A(); } My goal is to unit test function B by mocking out function A to see if it is called. Here is the code I h ...

MD Autocomplete Component: An Input Inside

Currently, I am working on implementing a feature where users can enter different search terms in an input field within Angular Material's autocomplete component. The issue arises when the user clicks on the input option as it closes the autocomplete ...

After reloading the component, I encountered difficulties subscribing again to the BehaviorSubject for a second time

After reading recommendations to always unsubscribe when removing a component, I encountered an issue in my code. The error object unsubscribed occurs when navigating between child components and trying to resubscribe to a BehaviorSubject. Even though I am ...

Transferring a document through an Angular form group and sending it to a Django API

I'm facing an issue with a form in Angular that contains multiple entries such as name, email, phone number, and a file field. I have grouped all these elements using a Form group. The corresponding model is in Django (utilizing Django Rest Framework) ...

Having trouble properly displaying information from a JSON array with jQuery

Having a basic array of data in a JSON file is presenting a challenge for a beginner like me when it comes to extracting the data. Here is the array that I have access to: var clients = [ { "clientid": "456489", "client-name": "John Smith", "e ...

Incorporating a sidemenu into a DOM using Ionic2 and Angular2 Typescript

I am currently struggling to properly integrate the sidemenu from the app.ts file. app.html: <ion-menu [content]="content"></ion-menu> <ion-nav id="nav" [root]="rootPage" #content ></ion-nav> app.ts import {App, IonicApp,Page, ...

Securely administering Active Directory from a remote machine

I have recently developed an ASP.NET website that needs to interact with an Active Directory located on a separate server to change user passwords. The challenge I am facing is the authentication process, as I must authenticate using an existing AD account ...

Toggle the display of input fields based on radio button selection in Angular 2

We want to dynamically display additional input fields based on the selected radio button. Radio <div class="form-group"> <label>What would you like to evaluate?</label> <div class="radio"> <label> ...

Having trouble with jQuery find and attribute selectors?

On my webpage, there is a form where: The command $('form').find('input[type=submit]') returns [undefined] However, using $('form input[type=submit]') works correctly... Is this behavior expected? ...

having difficulty implementing accordion feature in foundation 5

I'm attempting to implement an accordion feature in foundation 5, but unfortunately, it's not functioning as expected. Can someone please point out where I may be going wrong? <!DOCTYPE html> <html> <head>     <link rel ...

Upgrading embedded data in MongoDB using Mongoose

I have been attempting to modify the nested value data1 within a MongoDB document: { "content": { "data": { "data1": "Some data", "data2": "Better data" }, "location ...

Testing @microsoft/applicationinsights-web within an Angular project on a local environment

How can I test Microsoft's application insights locally? Most guides I've come across suggest testing it on the Azure portal, but I can't do that as it would mean testing it in a production environment. ...

Issue with JQuery Mobile: Inconsistent page navigation functionality

I am currently utilizing JQuery Mobile along with MVC4. MARKUP: <div data-role="page" data-theme="d" id="main"> <div data-role="header"> <h1>Test Page</h1> </div> <div data-role="content"> & ...

Issue with PrimeNG DataTable contextMenu alignment inside TabView

I encountered an issue with displaying a DataTable - contextMenu when it is placed within a TabView. The contextMenu was appearing off-center. However, the DataTable - contextMenu worked perfectly fine when it was not wrapped in a TabView. To address this ...

Oops! The formGroup function in Angular 5 requires an instance of a FormGroup

While working with Angular 5, I encountered an error in this basic form. Here is the issue: Error Message: EditVisitanteDialogComponent.html:10 ERROR Error: formGroup expects a FormGroup instance. Please pass one in. Example: > > &l ...