Angular 2 - 如何在 *ngFor 中传递函数

Angular 2 - how to pass function in *ngFor

我需要有关如何在 *ngFor 循环中传递函数或任何其他建议的帮助??

我有 todo-list 组件和一个子 todo-item 组件 - 我想传递一个函数,它将 return 一个值 - 请检查下面的代码:

-- 待办事项列表组件

`<div class="list-group">
  <app-todo-item 
    *ngFor="let todo of todos; let i = index"
    [todoItem]="todo"
    [index]="i"></app-todo-item>
</div>`

-- Todo 项目组件 `

<a 
  [routerLink]="index"
  [routerLinkActive]="'list-group-item-warning'"
  class="list-group-item">
  {{ todo.name }}
  <span class="badge badge-pill" 
    [ngClass]="{'badge-success': todo.status === 'active', 'badge-warning': todo.status === 'inactive'}">{{ todo.status }}</span>
  <div class="option-group float-right"> 
    <span class="badge badge-dark">2 days ago myFunction(date)</span>
  </div>
</a>
`

请告诉我有什么可能的方法可以实现这一点。 提前致谢

您是否尝试将函数传递给 app-todo-item 组件?

如果是这样,您可以使用 angular 核心

中的 @Output
// import it inside your component
import { Output, EventEmitter } from '@angular/core'

// declare the function callback you want to recieve
@Output() callback = new EventEmitter();

// to make the callback send data back call, if you want to pass multiple fields put it all inside an object
this.callback.emit(datatobepassed)

// to make use of it do; you need to put $event or else function recieves undefined
<app-todo-item (callback)=”yourfunction($event)”>

// in your parent component
yourfunction(data: any)
{
    // stuff
}

希望对您有所帮助