deseosuho deseosuho - 1 month ago 25
TypeScript Question

angular2 event listening on *NgFor iterative variable

I've been exploring angular2 as a way to solve a particular data binding challenge.

I have a javascript array of objects, essentially a database recordset, which I present in a UI as an html table. I have various menus and inputs on each row to allow the user to modify the underlying recordset.

The overall workflow is that the user loads a recordset from an external database, manipulates it in UI, then commits the edits back to the database.

Below is a typescript code snippet of the data table component:

@Component({
selector: 'employee_table',
template: `
<h2>{{ title }}</h2>
<table>
<tr>
<th colspan=6>Name</th>
<th>Level</th>
<th>Rating</th>
<th>Suggested Total Pay</th>
<th>Total Pay Override</th>
<th>Comment</th>
<th></th>
<th></th>
</tr>
<tr *ngFor="#ee of ee_data" [className]=ee.tr_classes [class.selected]="ee.is_selected">
<td *ngFor="#x of ee.mgmt_spacer"></td>
<td [attr.colspan]="[6-ee.mgmt_tier]">{{ee.name}}</td>
<td>{{ee.level}}</td>
<td>{{ee.rating}}</td>
<td>{{ee.suggested_tct | currency:'USD':true:'1.0-2'}}</td>
<td><input type="text" placeholder="e.g. $100,000"></td>
<td><textarea rows="1" placeholder="Explain Override" autoGrow ></textarea></td>
<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>
</tr>
<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){
alert('HEY! '+event.target+'; '+event.target.value);
}

}


I'm struggling with how to use the event listener defined in the template to pass a handle for the javascript object to
drToggle()
.

I would like to expose the underlying javascript array (the recordset
ee_data
) to a processing function that edits that recordset, leaving angular to automatically update the html.

However, it seems that all I can do is pass the $event keyword. I could conceivably interrogate
$event.target
to get the parent
<tr>
, then look in the html values of its
<td>
elements to find enough info to locate the corresponding record in the javascript object, but this seems very roundabout.

In the ts template, there is a iterative variable
#ee
that is used to build out the html table from the javascript array. Is there any way I can pass this same
#ee
variable to my event listener directly?

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

You can just pass the iteration variable ee

The syntax to declare a variable in *ngFor is let instead of # since several months already.