Search code examples
angulartypescriptangular2-services

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


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

Solution

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