【问题标题】:Angular 2 - how to pass function in *ngForAngular 2 - 如何在 *ngFor 中传递函数
【发布时间】:2018-02-06 14:45:13
【问题描述】:

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

我有 todo-list 组件和一个子 todo-item 组件 - 我想传递一个返回值的函数 - 请检查以下代码:

-- 待办事项列表组件

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

-- 待办事项组件 `

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

请让我知道我可以通过什么方式实现这一目标。 提前致谢

【问题讨论】:

    标签: angular2-template angular2-directives


    【解决方案1】:

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

    如果是这样,您可以使用角核心中的@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
    }
    

    希望对你有帮助

    【讨论】:

    • 如果我想在待办事项模板中打印我的回调函数值怎么办??
    • 这是否意味着回调函数将数据发送回app-todo-item组件?
    猜你喜欢
    • 2023-03-03
    • 2018-10-20
    • 1970-01-01
    • 2016-06-22
    • 2017-07-23
    • 2017-09-20
    • 2016-08-28
    • 2017-02-12
    • 2019-10-20
    相关资源
    最近更新 更多