Kingsley
Kingsley

Reputation: 805

How can I pass an index variable from Angular 5's ngFor to a component method?

I have a list of images that I'm looping over and displaying in the browser. Each image has a click handler which only accepts one argument - the image's index. The problem is, I can't quite figure out how to pass that index to the method.

<img *ngFor="let img of images; let i = index"src="{{img}}" alt="{{i}}"   
(click)="doSomething({{i}})">

I'd like to be able to pass that 'i' into the doSomething() method but I can't quite figure out how to without getting an error. Help.

Upvotes: 0

Views: 43

Answers (1)

Chris White
Chris White

Reputation: 30089

Just remove the template braces - the (click) event callback is just plain JS so you can call:

(click)='doSomething(i)'

Upvotes: 1

Related Questions