当函数接受参数时,如何正确地将函数从父组件传递给子组件?
在ngOnInit中,如何确定函数的范围,例如:
addToList(id) {
this.store.dispatch(this.listActions.addToList(id));
}
ngOnInit,这是错误的。
ngOnInit() {
this.addToList = this.addToList.bind(this, id);
}
在我的父组件中,我具有
addToCart(id)
函数。我想将该函数传递给我的子组件,该子组件具有项目列表,并且在单击某个项目上的ADD按钮时,我想将addToCart(item_id)回调给父组件。
最佳答案
@Maarek的答案是一个很好的答案,而且可能是这样做的“正确”方法。我在这里介绍的是一种更简单的方式,专门用于从 child 到 parent 的交流。
您在原始帖子中建议的是让Parent向 child 发送回调方法,以便 child 可以在适当的时候使用数据进行调用。为了使用事件来完成此特定任务(从子对象到父对象的数据,涉及子对象中的某些操作),可以使用子对象内部的EventEmitter来完成。请参阅此API引用,其中包含一个示例:https://angular.io/docs/ts/latest/api/core/index/EventEmitter-class.html和我作为演示制作的这个Plunker:https://embed.plnkr.co/T1wFqVOhMXgX6NRfTuiC/
在 child 中,您有如下代码:
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'item',
template: `
<div class="item">
<button type="button" (click)="addItem()">Add</button>
<p>{{id}}
</div>
`
})
export class ItemComponent {
@Input() id: string;
//key line here: this emitter can be bound to by parent to get notifications
@Output() add: EventEmitter<string> = new EventEmitter<string>();
constructor() { }
addItem() {
//then when the button is clicked, emit events to the parent.
this.add.emit(this.id);
}
}
父级将调用创建组件,如下所示:
<item id="1" (add)="addToList($event)"></item>
其中addToList()
是Parent上的一个函数,可以完成回调打算完成的工作。 $ event是从子代(id)传递的数据。关于javascript - Angular 2如何将带有参数的函数传递给子组件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39044582/