0

So I have the following:

<div *ngFor="let career of careers">
    <label>{{career.name}}</label>
    <input type="checkbox" attr.id="{{career.id}}" (change)="doSomethingWithId($event.target)"
</div>

The TS Component:

doSomethingWithId(target: Element): void {
     console.log(target.attributes.id);
}

The id here gives an error:

Property 'id' does not exist on type 'NamedNodeMap'.

I don't know if attr.id is the best way even or if it should just be id, or even data-id. But I need to get the career.id of what was clicked on.

1 Answer 1

1

The binding for your id is wrong. Change this

 attr.id="{{career.id}}"

to this

[attr.id]="career.id"

Update 1 If you just want the career id, you can just pass it directly in your function like this

<input type="checkbox (change)="doSomethingWithId(career.id)"

and in your service

doSomethingWithId(target): void {
     console.log(target);
}
Sign up to request clarification or add additional context in comments.

8 Comments

I think you can do it either way can't you? Either way, I changed it but the same error exists. Is attr.id the best way to do this or should I be using like data-id?
If he wanted to use interpolation, he can just leave off the 'attr' part. id="{{ career.id }}"
@Samir why not just pass the career id in your function? you don't need to set the id in your input to get it. If that's what you want I can update my answer
@Samir glad to help
its true. that's def the smarter way to do it if you're using discrete mouse listeners for each item. When I have ngFor loops, I usually try to put a single mouse event listener on the parent element, and then delegate click actions based on the srcElement.id attribute of the click $event. I'm not really sure if it actually benefits performance that much, bc in one case you're adding a bunch of mouse listeners, and in the other case you're adding a bunch of attribute bindings. Angular can't really do "one time" binding so those bindings stay active even though their value doesn't change.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.