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

Bringing an AMD module into a Mocha test

I recently encountered an error while using Mocha to test code that was exported as an AMD module. When running the Mocha test, I received the following error message: ReferenceError: define is not defined at Object.<anonymous> (/home/malintha/proje ...

Access to property 'foo' is restricted to an instance of the 'Foo' class and can only be accessed within instances of 'Foo'

In my Typescript code, I encountered an error with the line child._moveDeltaX(delta). The error message reads: ERROR: Property '_moveDeltaX' is protected and only accesible through an instance of class 'Container' INFO: (me ...

Is it possible to make the entire div clickable for WordPress posts, instead of just the title?

I am currently facing an issue where only the h1 element is linked to the post, but I want the entire post-info div to be clickable. Despite my efforts, I haven't been able to make the whole div clickable, only the h1 element remains so. Below is the ...

"Enhance Your Website with Multiple Video Streams using YouTube API Events

Hello everyone! I am looking to include multiple videos on my website and have them start playing automatically when a user scrolls and the videos are in view. I want the speakers to be muted by default using the mute() function. Previously, I had succes ...

Show two choices in a select box next to each other

I've been attempting to display a select box with two options side by side in a list format. Struggling to find any libraries that can achieve this functionality. Here is an example: <select> <option x><option y> <optio ...

Choose the currently active md-tab within the md-dialog's md-tab-group

I need to create a dynamic md-dialog with an md-tab-group that has two tabs. The md-dialog should open based on the button clicked, displaying the corresponding tab content. The initial template where the md-dialog is triggered: <button md-button class ...

By using providedIn: 'root', services are automatically registered for testing

It could be due to the new functionality, but when I have a service like this: @Injectable({ providedIn: 'root' }) export class MyService {...} and my MyComponent uses it. When testing that component, I simply do this and it works! TestBed.c ...

Executing the Javascript function after the dynamic loading of the table through an ajax request

After the table finishes loading, I would like to trigger a JavaScript function. Originally, I considered using the onload() function on the table, but I discovered that it does not actually work for tables. ...

The function JSON.parse appears to be malfunctioning within the code, yet it operates smoothly when executed in

I am facing an issue with my Angular $http post service that communicates with a WCF service. The success handler in the http post is as follows: .success(function (data) { var response = JSON.parse(data); var tsValid = response.Outcome; defer ...

Error: The NgTools_InternalApi_NG_2 member is not exported in compiler-cli/src/ngtools_api

Currently, my ng serve command is not working and showing the following error message: ERROR in node_modules/@angular/compiler-cli/index.d.ts(20,10): error TS2305: Module '"./node_modules/@angular/compiler-cli/src/ngtools_api"' has no expor ...

Error encountered while using Jquery's .each() method on a DOM element and attempting to

Trying to utilize the each() function on my DOM to dynamically retrieve a field, I encountered an issue with the following code: var new_entry = new Object(); $('div[name="declaration-line-entry"]').each(function () { new_entry.name = $(this ...

Retrieve individual item

It has been a few days since I started working on this. I am attempting to create a query that retrieves all businesses registered in a specific city. Subsequently, for each business, I aim to fetch all products associated with that business and then cons ...

Tips for utilizing the forEach method in Angular 2 without relying on ngFor?

I recently started learning Angular 2 and I am trying to figure out how to access array details using a forEach loop and apply certain conditions on it. Once I make the necessary changes, I want to display this data using ngFor. In Angular 1, this was ea ...

What is the procedure for assigning an element's background-color to match its class name?

Is there a way to use jQuery to make the background color of a span element match its class? $(function() { $("span").css("background-color") }); span { display: inline-block; width: 5px; height: 5px; border: solid #0a0a0a 1px; } <script src= ...

No results found by Mongoose find() method

I've set up a route that utilizes a model named Todo as shown below: app.get('/api/todos', function(req, res) { Todo.find({},function(err, todos) { if (err) res.send(err); console.log("number of todos " + tod ...

How Can I Build a Dynamic Field Form Builder in Angular 4?

While working with dynamic JSON data, I needed to create fields dynamically. For instance, if my JSON array contains 3 values, I would generate 3 input checkboxes dynamically as shown below: <ng-template ngFor let-numberOfRow [ngForOf]="numberOfRows"&g ...

Sending data from child components to parent components in Angular

I'm facing an issue with retrieving data from a child array named store within user data returned by an API. When trying to access this child array in my view, it keeps returning undefined. Code export class TokoPage implements OnInit { store= nu ...

Is there a way to temporarily halt a jQuery animation for 2 seconds before automatically resuming it, without relying on mouse-over or mouse-out triggers?

With just one scrolling image implemented in jQuery, the logos of clients are displayed continuously in a scrolling box with no pauses. Speed can be adjusted easily, but pausing and then resuming the animation after 2 seconds seems to be a challenge whic ...

Encountering issues with accessing image files located in the public folder of my Next.js project - Receiving a 404 Error message

I am currently facing an issue with my Next.js project where I am unable to use image files from the public folder. Despite checking that the file paths, names, and extensions are correct, as well as ensuring my configurations are accurate, I keep encounte ...

Tips for including an external .js file in a .php file

In an attempt to call a JavaScript function located in an external file, I am facing some issues. Here is my folder structure: C:\xampp\htdocs\test\index.php C:\xampp\htdocs\test\js\functions.js index.php &l ...