Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass the index value of a ngFor loop into the component? [duplicate]

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>`
like image 789
Umair Khan Avatar asked Jun 18 '17 06:06

Umair Khan


1 Answers

<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.

like image 195
Aravind Avatar answered Oct 17 '22 03:10

Aravind