0

Angular 2 Version:rc.1

I am returning a list of names and places in a table using *ngFor and I want to bind the data to the cell that I click on to a variable in my component.

component.html

<tr *ngFor="let result of Results$">
  <td #foo (click)="passValue(foo)">
    {{result?.name}}
  </td>
  <td>
    {{result?.place}}
  </td>
</tr>

component.ts

passValue(foo) {
  this.value = foo;
  console.log(foo);
}

In the console I am getting the following when I click on a cell with "John" as its value:

<td _ngcontent-pof-13="">
    John
</td>

Ideally, the console would just log "John" instead of the entire td element.

Or maybe there is an entirely different and better way to do it.

Any ideas?

1 Answer 1

1
<tr *ngFor="let result of Results$">
   <td #foo (click)="passValue(foo)">

#foo here is a template reference variable - a reference to the DOM element itself. result is a reference to the data you're binding to - in this case, an object with name field with value "John":

So, replace

<td #foo (click)="passValue(foo)">  // prints the td element 

by:

<td #foo (click)="passValue(result?.name)"> // prints "John"
Sign up to request clarification or add additional context in comments.

8 Comments

result is the entire object; wouldn't you want to pass result.name if you wanted the console to print "John" in passValue?
Yes, Metro Smurf that is what I ended up doing and it worked
@MetroSmurf good eye, thanks for pointing that out. answer updated.
It actually did not need the ? operator here, but for some reason I need it for displaying the values
@EricScandora - that's called the Elvis operator, you should google it. It prevents the error that would otherwise occur if result was undefined when the template is drawn
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.