Issue with Angular 8: click event is not triggering when using ngFor directive to iterate through arrays of objects

Update: The original post has been modified to omit implementation details and complexity.

I am facing an issue with an ngFor loop that invokes a method on a service. The method returns an array which is then iterated over by the for loop.

The click event binding does not function properly when the returned array consists of objects. However, it works fine when the array contains primitive types.

***Notably, contextmenu or right-click events work in both scenarios, indicating that the problem lies specifically with the click event.

***Interestingly, click events immediately preceding and following this particular section work as intended.

***The behavior persists even if I transfer the hardcoded method from the service to the component.

Below is the snippet of code where the issue occurs:

<div><span (click)="addVariable()"></span></div> <!-- works -->

<div *ngFor="let variable of designerService.getVariables();" (click)="onLeftClick()" (contextmenu)="onRightClick()">just a simple div</div> <!-- doesn't work -->

<div><span (click)="addVariable()"></span></div> <!-- works -->
public addVariable() {
  alert("add variable");
}

public onLeftClick() {
  alert("left click");
}

public onRightClick() {
  alert("right click");
}

When utilizing the following implementation (or any other object type array), the click event fails to trigger:

public getVariables(): {name: string}[] {
  return [{"name": "dog"},{"name": "cat"},{"name": "bird"},{"name":"bear"}];
}

However, when using this implementation, the click event functions properly:

public getVariables(): number[] {
  return [1,2,3,4,5];
}

This issue seems quite straightforward yet persists...

Any suggestions on what might be causing this problem? I feel stuck with Angular at this moment.

Answer №1

Give this a try:

// YourComponent ts file
variables: {name: string}[];

constructor(public designerService: DesignerService) { }

ngOnInit() {
  this.variables = this.designerService.getVariables();
}

// Other methods
<!-- HTML template file -->
<!-- Instead of calling designerService.getVariables() method, use the component property 'variables' -->
<div *ngFor="let variable of variables" (click)="onLeftClick()" 
(contextmenu)="onRightClick()">works</div> <!-- works -->

It's possible that there is code in the application triggering Change Detection, causing re-rendering before the click handler runs and causing the issue.

You can also try creating an array property in the service class as a test, returning that array from getVariables(), to see if it helps resolve the problem.

// DesignerService ts file
someArray = [{"name": "dog"},{"name": "cat"},{"name": "bird"},{"name":"bear"}];

public getVariables(): {name: string}[] {
  return this.someArray;
}

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

Utilizing modal functionality in CakePHP 3 (or: Incorporating JavaScript within Controllers)

I have a typical form that was created using cake/bake. After the form is submitted, my controller checks a simple condition: If condition A is met, it will just save the data using patchEntity($foo, $this->request->getData()) If condition B is me ...

Exploring Vue and Webpack: Optimizing global variables for development and production environments

I have been using vue-cli to create my web application. Throughout the app, I am making use of an API by including it in various places like this: axios.post(API + '/sign-up', data).then(res => { // do something }); The API variable is a c ...

Angular: Keeping all FormControls in sync with model updates

I am dealing with a collection of FormControls that were created using FormBuilder: this.someForm = this.fb.group({ name: '', size: '', price: '', }); Is there an alternative method to update them based on ...

Combining Two Tables Using jQuery

I am currently attempting to combine two tables into one using jQuery in the following manner: var table = document.createElement("table"); table.id = "mergedTable"; $("#mergedTable > tbody:last") .append($("#csvInfoTable2 > tbody").html()) ...

What is the best approach for creating a test case for a bootstrap-vue modal component

Exploring ways to effectively test the bootstrap vue modal display function. On the project page, the modal toggles its visibility using the toggleModal method triggered by a button click. The modal's display style is switched between 'none' ...

Tips for adding spacing when the sidebar collapses and expands in a React application

I am attempting to achieve a layout where the body adjusts its space when the sidebar collapses and expands. Here is how it appears when the sidebar expands: see expanded sidebar here And this is how it looks when the sidebar collapses: see collapsed s ...

Analyzing a tweet containing unique characters

I am currently working on extracting links from tweets, particularly hashtags and mentions. However, I have encountered an issue when the tweets contain special characters like " ...

Data is not being stored in Parse

I am currently facing a challenge while working with Parse for Javascript: When users sign up, along with their username and password, I also need to save their first and last names in Parse. However, at the moment, only the username and password are bein ...

Controller function failing to trigger

I'm new to asking questions, so if I've made a mistake, please let me know. I've searched for an answer here but couldn't find one. Any help would be greatly appreciated. I'm attempting to load a list of "Countries" using a contro ...

Error: The module '@angular/localize/init' could not be located within the specified directory '/usr/src/app/src'

After upgrading from Angular 8 to 9, I added the @angular/localize package. In my polyfill.ts file, I included the following import: import '@angular/localize/init'; When I compile and run my app locally in a browser, everything works fine. How ...

There are various IDs in the output and I only require one specific ID

I have a JSON fetcher that is functioning properly. However, whenever I request an ID, it returns all the IDs present in the JSON data. Is there a way to retrieve only the latest ID? This is my first time working with JSON so I am still learning. $(docu ...

Tips for Receiving Error Messages with Patterns in Angular 2

After several attempts, I am unable to get this code to function correctly. <div> <span *ngIf="!usernameRef.errors?.required">Amount</span> <span *ngIf="!usernameRef.errors?.required">Cover amount is necessary.</span& ...

The useState variable's set method fails to properly update the state variable

I am currently developing an application with a chat feature. Whenever a new chat comes in from a user, the store updates an array containing all the chats. This array is then passed down to a child component as a prop. The child component runs a useEffect ...

The function 'sendEmailVerification' is not a property of the type 'Promise<User>'

Hey there, I've been working on my ionic4 app and have encountered an issue with the sendEmailVerification function. The console is suggesting that I may have forgotten to use 'await'. Any ideas on how to resolve this? Thank you. import { In ...

Running JavaScript code within views

While dealing with AngularJS, I have an index page that includes a <div ui-view></div>. When a specific URL like #/offers/new is entered, it loads a page such as new-offer.html into the ui-view. In my javascript code block within the index.htm ...

Unable to resolve all dependencies for UserService: (Http, ?)

After transitioning to the latest Angular2 version 2.0.0-beta.17, my project started experiencing issues. The structure of my UserService is as follows: import { Injectable} from '@angular/core'; import { Http } from '@angular/http'; ...

Navigating without the need for a mouse click

Is there a way to automatically redirect without user interaction? I need the redirection to happen without clicking on anything <script> setInterval(function(){ window.location.replace("http://your.next.page/"); }, 5000); // Redirec ...

Something seems to be amiss with the validation functionality in jQuery

After creating a simple form with input fields and a button, I added validation to display an error message when clicking the apply button without filling out required values. However, the code is not functioning as intended. Even though error messages are ...

Establish a value for the attribute of an HTML tag

Can anyone assist me with setting the attribute value for the following HTML tag using Selenium WebDriver? For example, I need to change 50% to 70% either via JavaScript with WebDriver or a simple WebDriver script. I have tried several options but this pa ...

Create a duplicate array with all distinct elements - JavaScript

Help needed: I am facing an issue with an array of objects. My goal is to create a unique copy of this array to prevent any changes in the original one when modifications are made to the new array. I have experimented with several methods, including: let ...