【问题标题】:How to use ngFor index variable in child component如何在子组件中使用 ngFor 索引变量
【发布时间】:2016-08-12 20:48:09
【问题描述】:

我使用 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;
  }

}

我希望我已经解释得很好,如果您需要更多信息,请告诉我!

【问题讨论】:

    标签: javascript angular angular2-template ngfor


    【解决方案1】:

    您可以将其作为输入提供:

    <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;
      (...)
    }
    

    【讨论】:

    • 该参数仅在ngOnInit 中可用,并且在此方法被触发后...您何时/何处尝试使用该属性并且它未定义?
    • 我对 ngOnInit 并不完全熟悉,我将如何实现它?当用户单击“编辑按钮”时,它会调用 TaskService 中的一个方法,该方法只是控制台记录结果(目前)。
    • 只需在您的组件中添加一个ngOnInit 方法。您可以尝试在其中显示索引值:console.log(this.index);
    • 哦,task-actions 组件还有另一个层次。您还需要为其提供索引...
    • 当我第一次遇到语法错误时它会起作用,当我应该使用 index 时,我仍然在我的 HTML 模板中使用 i - 非常感谢! :)
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    • 2012-05-20
    相关资源
    最近更新 更多