Alicia C
Alicia C

Reputation: 150

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>
</li>


//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>
</div>


//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 = [];

  editTask(i){
     this.editable[i] == true;
  }

}

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

Upvotes: 1

Views: 6271

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202176

You could provide it as an input:

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

And in your TaskItemComponent class:

@Component({
  selector: 'task-item',
  (...)
})
export class TaskItemComponent {
  @Input()
  index: number;
  (...)
}

Edit

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:

@Component({
  selector: 'task-actions',
  (...)
})
export class TaskItemActionsComponent {
  @Input()
  index: number;
  (...)
}

Upvotes: 2

Related Questions