0

It's probably a really simple question, but I can't find my answer. how and what is the best approach to send attributes or any item property binding of an item through the click event?

Consider:

<item class="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 class="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 its 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 the attributes/bindings of a clicked element itself?

1
  • 2
    Believe you want currentTarget, it's also typical to have properties like this in the TS so can bind to them in the view as opposed to trying to select values of attributes off of elements (ie why not just clickItem(item.id) or clickItem(item)). If you need to access a specific DOM element within a component typically best to use ViewRef (again usually prefer have things defined in TS and bound into the view instead of reading things out of the DOM/view). Commented Jan 4, 2023 at 2:40

1 Answer 1

1

You can achieve this with Template Reference Variable.

<item 
  class="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);
}

Demo @ StackBlitz

Sign up to request clarification or add additional context in comments.

Comments

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.