简体   繁体   中英

Angular2: click listener with *ngFor

I'm trying to create a list of components and to attach a click event listener that registers the index of the component clicked.

I can achieve this by attaching the event listener at my leaf node, as it knows its index. But then I have to bubble the event up one more time than I might need to. What I'd prefer to do is have the following at the parent of the leaves:

  template: `
    <trackpoint
        *ngFor='#tp of lapData; #i=index'
        [tp]='tp'
        [index]='i'
        [ngClass]="{selected:selectedTps[i]}"
        (click)='handleClick($event)'>
    </trackpoint>
  `,

and in my controller

handleClick(e:MouseEvent) {
   console.log(e);
   this.lapEventHandler.next({
   // I want to be able to access i from the template
  });
}

I've been examining the the MouseEvent object but although I can find the Trackpoint among the event parents, I cannot find the index property. Am I trying to do the impossible.

Try with

(click)='handleClick($event, i)

and

handleClick(e:MouseEvent, i: any)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM