Listening to events on the iterative variable of NgFor directive in Angular 2

Angular2 has been my latest exploration in solving a unique data binding challenge.

In my UI, I've presented a javascript array of objects like a database recordset in an HTML table. Each row contains menus and inputs allowing users to modify the recordset. The workflow involves loading a recordset from an external database, making changes in the UI, and committing edits back to the database.

Here's a snippet of typescript code for the data table component:

@Component({
selector: 'employee_table',
template: `
        <h2>{{ title }}</h2>
        <table>
            ... (omitted for brevity)
                <td class="txt_btn dr_toggle_btn"
                        (click)="drToggle($event)">{{ee.show_direct && '-' || '+'}}</td>
                <td class="txt_btn desc_toggle_btn">{{ee.show_descendants && '--' || '++'}}</td>
            ... (omitted for brevity)
        <table>
        <span class="table_return">Back to Top</span>
            `,
    providers: [EmployeeTableService],
    directives: [AutoGrowDirective]
})
export class EmployeeTableComponent{
    title: string = "Employee Data";
    ee_data;

    constructor(employeeTableService: EmployeeTableService){
        this.ee_data = employeeTableService.getData();
    }

    drToggle(event){
         // functionality here
    }

}

I'm facing difficulty using the event listener defined in the template to pass a handle for the JavaScript object to `drToggle()`.

My goal is to expose the underlying JavaScript array (`ee_data`) to a function that edits the recordset, letting Angular handle the HTML updates automatically.

Currently, all I can do is pass the `$event` keyword. Although I could go through `event.target` to find necessary information about the corresponding record in the JavaScript object, it seems quite indirect.

Is there a way I can directly pass the iterative variable `#ee`, used in building the HTML table from the JavaScript array, to my event listener?

Answer №1

<tr *ngFor="let ee of ee_data"
...
(click)="drToggle(ee)"

Simply pass the iteration variable ee

The correct syntax for declaring a variable in *ngFor is to use let instead of #, which has been the standard for several months now.

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

Having trouble understanding how to display an HTML file using Next.JS?

Currently, I am working on a project that involves utilizing Next.JS to develop a webpage. The main goal is to display a PDF file on the left side of the screen while integrating Chaindesk on the right side to create a chat bot capable of extracting inform ...

What is the best way to retrieve the border-color inline style using jQuery?

I have a HTML tag like this. <span id="createOrderFormId:accountNo" style="border-color: red;"><</span> To retrieve the style value for the border-color property, I tried using the following jQuery code: $( document ).ready(function() { ...

Utilizing highcharts to visualize non-linear time data pulled from a CSV file

I am seeking guidance on implementing a simple graph based on data from a CSV file in web development. I lack experience in this area and have struggled to find a suitable example to follow. The CSV file contains data in the format of a unix timestamp, hu ...

Is it possible to link actions to a storage location external to a component?

Imagine having a store set up with a middleware called redux-thunk. The store is created and exported using the following code: import myOwnCreateStoreMethod from './redux/createStore'; export const store = myOwnCreateStoreMethod(); Now, you ha ...

Enhancing Communication Between JavaScript and PHP

Positioned within my form is an input field where users can enter their postcode. The shipping cost for their order will be determined based on this postcode, utilizing PHP to assign different costs depending on the zone. After the user enters their postc ...

Removing an item from an array in Mongoose

I'm encountering an issue with removing an Object from an Array and I'm unsure of the correct way to use $pull for this action. Any help would be greatly appreciated! JSON data "accountId": "62efd8c008f424af397b415d", "l ...

Is it possible to access a sub property using a dot string in Vue 3?

Given a Vue 3 proxy object structure as shown below: <script> export default { name: "test", data() { return { users: [{ "id": 1, "name": "Leanne Graham", " ...

Unforeseen alterations in value occur in JavaScript when converting to JSON format

Having trouble generating a gantt chart from a JSON string, specifically with parsing the JSON string into a JSON object. I have a variable myString containing a JSON string that looks like this: {"c": [{"v": "496"}, {"v": "Task name 1"}, {"v": "9, "}, { ...

What is the best method to update the content of one div with content from another page using AJAX?

Having trouble achieving smoother page loads? My goal is to utilize AJAX to specifically fetch a certain div from another page and then swap out the content of a div on this current page with the response. Below is my JavaScript script that uses AJAX to r ...

Which library does stackoverflow utilize to showcase errors (utilizing Bootstrap popover for error help-block)?

Currently, I am using bootstrap's has-error and help-block classes to display validation error messages in my form. However, I find the error message display in Stackoverflow's Ask Questions Form to be very appealing. Are they using a specific js ...

What is the best way to incorporate user input and output functionality in a React Javascript application with Material UI for a seamless display?

I am trying to achieve a similar output as shown in this code http://jsfiddle.net/6vqd4vnq/ but using material ui/reactjs. Is there something missing in my setup that is preventing the content from being displayed correctly like in the provided link whic ...

Simple code styling tool

Seeking guidance to create a basic syntax highlighter using JavaScript or ClojureScript. While aware of existing projects like Codemirror and rainbow.js, I'm interested in understanding how they are constructed and looking for a simple example. Do th ...

Configuring CORS settings in Angular-cli

Upon making a request to my backend url http://docker-users:5500/users?all=true, which returns a list of users, I encountered an issue with Angular-CLI's localhost url: http://localhost:4200. Even after configuring the proxy.config.json file and addin ...

React treats flat arrays and nested arrays in distinct ways

After some experimentation, I discovered an interesting behavior in React when passing nested arrays. Surprisingly, React renders the items properly without complaining about missing keys on the elements. const stuff = 'a,b,c'; // Nested Array ...

Issue encountered: Inability to implement asynchronous functionality within a forEach loop while making an API request

When making a GET API call, the code looks like this router.get('/review', async (req, res) => { try { const entity = await Entity.find(); const entityId = []; Object.keys(entity).forEach((key) => { entityId.push(entity[ ...

``I am experiencing issues with the Ajax Loader Gif not functioning properly in both IE

I am brand new to using ajax and attempting to display a loading gif while my page loads. Interestingly, it works perfectly in Firefox, but I cannot get it to show up in Chrome or IE. I have a feeling that I am missing something simple. The code I am using ...

How to effectively expose a node controller function for testing in Mocha

Below is the code for my foo-controller.js. module.exports = function(params) { var router = require('express').Router(); var db = params.db var controller = {}; controller.getFoo = function (req, res) { // logic to ret ...

Incorporate HTML and JavaScript to dynamically show a button when a specified condition evaluates as true and hide the button if the

I need help with a scenario where I want to show a button only when a specific variable reaches a certain value. For instance, if the variable equals 5, the button should be displayed; otherwise, it should be hidden. Here are the two buttons included withi ...

Ways to retrieve JSON string from responsetext in JavaScript

After spending the entire day on this, I still can't figure it out. I have AJAX that fetches a JSON string from a PHP script, but now I need to work with it in JavaScript. Here's what I've tried: var xmlhttp; xmlhttp=new XMLHttpRequest(); ...

Transferring information from a server action to a server component

Is there a way to transfer data from my server action, specifically the value of the temperature variable, to the Home server component in my nextJS14 app? I want to display this value in the jsx of my Home server component. How can I achieve this? impor ...