簡體   English   中英

如何在子組件中使用 ngFor 索引變量

[英]How to use ngFor index variable in child component

我使用 ngFor 從數組中創建了一個列表,並且我正在通過其他組件導入該列表的元素。

在我的列表組件中,我使用 ngFor 來獲取索引,我想在子組件中使用這個索引(見代碼)來創建動態變量,但我似乎無法讓它工作。

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

在“taskService”中,我有一個單擊方法稱為 - editTask(i) - 我希望能夠傳遞數組項的索引

我的課看起來像這樣:

export taskService {

  editable = [];

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

}

我希望我已經解釋得足夠好,如果您需要更多信息,請告訴我!

您可以將其作為輸入提供:

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

在您的TaskItemComponent類中:

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

編輯

由於要在操作組件中使用索引,因此還需要將其定義為輸入:

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

在您的TaskItemComponent類中:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM