It's probably a really simple question, but I just can't find my answer. how and what is the best approach to send attributes or any item property binding of an item through click event?
Consider :
<item [attr.data-itemid]="item.id" (click)="clickItem(attr.data-itemid)"> item1 </item>
// or send the whole element if sending property alone is not possible :
<item [id]="item.id" (click)="clickItem(this.id)"> item2 </item>
Get property in typescript :
clickItem(item): void {
console.log(item);
console.log(item.getAttribute('data-itemid'));
// using $event then .getAttribute() doesn't seem to be practical since it's sending
// the child element's event on click
}
I can't get this to work. Is there a way to send the attribute directly? if not, how to send the current item DOM and not it's children? I've tried using $event
property on click but accessing it through (event.target as Element).getAttribute('data-itemtype')
is a mess simply because the event is sending whichever element that is clicked, not the parent that has the event binding itself. and I don't wanna go through parent elements with Javascript it'd be a very messy approach.
What is the right way to send and access attributes/bindings of a clicked element itself?
CodePudding user response:
You can achieve this with Template Reference Variable.
<item
[attr.data-itemid]="item.id"
(click)="clickItem(itemElem)"
#itemElem
>
Item {{ item.id }}
</item>
With the above, you can pass the whole HTML element to the function.
To get the value of data-itemid
attribute:
clickItem(item): void {
console.log(item.attributes['data-itemid'].value);
}