2

I'm trying to get the id of the clicked anchor element. Here's my HTML:

 <div class="list-group col-md-4" *ngFor="let book of bookbook">
      <a href="#" class="list-group-item" id={{book.id}} (click)="selectBook($event)">
        <img src="{{book.image}}" alt="#">
        <p><strong>Price: ${{book.price}} | {{book.id}}</strong></p>
        <p>{{book.summary}}</p>
      </a>
  </div>

Here's the click function:

  selectBook(event){
      console.log(event.target.id)
  }

Any idea what I'm doing wrong here?

blankface
  • 5,757
  • 19
  • 67
  • 114

2 Answers2

3

you can pass book

(click)="selectBook(book)"
bipin patel
  • 2,061
  • 1
  • 13
  • 22
  • Now why didn't I think of that before haha. Thanks! Although I'd still like to know why getting the id via event object isn't working. – blankface Oct 28 '17 at 07:58
  • Adding a breakpoint inside `selectBook()`, you could inspect the event object. More from Angular docs: https://angular.io/guide/user-input#get-user-input-from-the-event-object – stealththeninja Oct 28 '17 at 08:09
  • Passing $event passes the MouseEvent object (type 'click'), not the list object – Richard Matsen Oct 28 '17 at 08:12
3

Please do not confuse target and currentTarget

event.target property contains a reference to the element the event happened on.

It is very important to understand that during the capturing and bubbling phases this target does not change: it always remains a reference to the element you clicked. It can be img, p or a in your case.

To know which HTML element is currently handling the event we should use currentTarget.

Now try

selectBook(event){
   console.log(event.currentTarget.id)
}

See also

yurzui
  • 205,937
  • 32
  • 433
  • 399