9

I have a ngFor loop in my code. and inside this ngFor loop I have a div, on clicking this div I want to pass the index value to the type script file.

I am new to Anglular 2 any help will be appreciated.

Eg:

`<div *ngFor="let y of characters;let i = index">
    <div (click)="passIndexValue()">
    </div>
<div>`
Umair Khan
  • 195
  • 2
  • 4
  • 15

1 Answers1

27
<div *ngFor="let y of characters;let i = index">
    <div (click)="passIndexValue(i)">
    </div>
<div>`


passIndexValue(index){
   console.log(index);//clicked index
}

You could also pass the value to the component like so (assuming below use of @Input)

<div *ngFor="let y of characters;let i = index">
    <childComponent [index]="i">
    </childComponent>
<div>`

And then pick up the value on the component object:

@Input() index: number;

And use it directly in the template of the child component like so:

<div id="mydivinstance_{{index}}"></div>

Thereby allowing a component to have a unique ID based on the *ngFor loop.

J E Carter II
  • 1,436
  • 1
  • 22
  • 39
Aravind
  • 40,391
  • 16
  • 91
  • 110