How to use ngFor index variable in child component

I have a created a list out of an array using ngFor, and I am importing in element’s of that list via other components.

In my list component, I am using ngFor to get the index, I would like to use this index within the child components (see code) to create dynamic variables but I can’t seem to get it to work.

//main list html template
<li *ngFor="#task of taskService.tasks; #i = index" class="list-group-item">
    <task-item [task]="task"></task-item>

//task item component html template
<div class="read-only">
    <label [contentEditable]="taskService.editable[i] == true" ng-model="task.title">{{task.title}}</label>
    <p [contentEditable]="taskService.editable[i] == true" ng-model="task.description">{{task.description}}</p>
    <task-actions [task]="task"></task-actions>

//task actions component html template 
<button type="button" (click)="taskService.deleteTask(task.title)"   class="btn btn-danger btn-xs">delete</button>
<button type="button" (click)="taskService.editTask(i)"     class="btn btn-info btn-xs">Edit</button>
<button type="button" (click)="completeTask()"  class="btn btn-success btn-xs">complete</button>

Within the ‘taskService’, I have a method on click called – editTask(i) – I want to be able to pass the index of the array item

my class looks something like this:

export taskService {

  editable = [];

     this.editable[i] == true;


I hope I have explained that well enough, let me know if you need more info!

Leave a Reply

1 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
newest oldest most voted
Notify of

You could provide it as an input:

<task-item [task]="task" [index]="i"></task-item>

And in your TaskItemComponent class:

  selector: 'task-item',
export class TaskItemComponent {
  index: number;


Since you want to use the index into the actions component, you also need to define it as input:

<task-actions [task]="task" [index]="index"></task-item>

And in your TaskItemComponent class:

  selector: 'task-actions',
export class TaskItemActionsComponent {
  index: number;