1

I use *ngFor for showing list of elements on a page. When user clicks on a particular element, that was generated from particular item of list. I want this item from the list to be passed to a function onChange(). But it only passing the first id for all elements in a function onChange(). In the same time, passing ids to function isChecked() works just fine. I think this behavior related with difference in processing between property binding [checked]="foo()" and event listening (change)="foo()"

<li *ngFor="let d of someList">
<div>
    <label for="checkbox>
        <input type="checkbox" id="checkbox"
               (change)="onChange($event,d.id)"
               [checked]="isChecked(d.id)">
        <span>{{d.value}}</span>
    </label>
</div>
<span>{{d.local}}</span>

But anyway how can I get desired behavior? Thank you.

UPDATE: Problem was solved, but some questions left.

changed my code on:

<li *ngFor="let d of someList">
<div>
    <label [attr.for]="'checkbox_'+d.id"
        <input type="checkbox" id="checkbox_{{d.id}}"
               (change)="onChange($event,d.id)"
               [checked]="isChecked(d.id)">
        <span>{{d.value}}</span>
    </label>
</div>
<span>{{d.local}}</span>

And it works. Then I took away html 'id' attribute from input, and it works as well. So what was a problem? As I can see, if many elements have the same id (when you don't generate it with loop), angular can't work properly with them. So you have to don't use 'id' attribute or generate it uniquely in loop. Is it right? Thank you.

2
  • Did you want the element to be passed to the method? Or the item from someList i.e. the value of 'd' Commented Mar 22, 2017 at 8:00
  • I wanted the property "id" of current item in the list was passed to the function when it called. Commented Mar 22, 2017 at 8:10

1 Answer 1

1
<li *ngFor="let d of someList">
<div>
    <label [attr.for]="checkbox_{{d.id}}">
        <input type="checkbox" id="checkbox_{{d.id}}"
               (change)="onChange(d.id)"
               [checked]="isChecked('checkbox_' + d.id)">
        <span>{{d.value}}</span>
    </label>
</div>
<span>{{d.local}}</span>
Sign up to request clarification or add additional context in comments.

1 Comment

fix your [attr.for]="checkbox_{{d.id}}" in answer on [attr.for]="'checkbox_'+d.id" And it works. Then I took away html 'id' attribute from input, and it works as well. So what is a problem? As I can see, if many elements have the same id, angular can't work properly with them, or what? Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.