[英]How to emit event from component loop to main parent angular 5
I wrote the below code, where I am looping component to display children 我写了下面的代码,我循环组件来显示子代
parent.component.ts parent.component.ts
tree = [
{
id: 1,
name: 'test 1'
}, {
id: 2,
name: 'test 2',
children: [
{
id: 3,
name: 'test 3'
}
]
}
]
nodeClicked(event) {
console.log(event);
}
parent.component.html parent.component.html
<app-child [tree]="tree" (nodeEmitter)="nodeClicked($event)"></app-child>
child.component.ts child.component.ts
@Input() tree;
@Output() nodeEmitter = new EventEmitter();
clickToEmit() {
this.nodeEmitter.emit(1);
}
child.component.html child.component.html
<ul>
<li *ngFor="let node of tree">{{ node.name }}</li>
<button (click)="clickToEmit()">Click Me!!!</button>
<app-child [tree]="node.children" (nodeEmitter)="nodeClicked($event)"></app-child>
</ul>
Here, my problem is 在这里,我的问题是
I am able to get emitted event in parent.component.html 我能够在parent.component.html中获取发出的事件
I am not able to get emitted event from child.component.html to 我无法从child.component.html获取发出的事件
parent.component.html parent.component.html
I am getting the error as nodeClicked is not defined in child.component.ts 我正在错误的nodeClicked不child.component.ts定义
What I am doing wrong here? 我在这做错了什么? I wasted so many hours of time on this issue.
我在这个问题上浪费了这么多时间。
Thank you for your help... :-) 谢谢您的帮助... :-)
In the child component you need to continue chaining the event up to the parent. 在子组件中,您需要继续将事件链接到父组件。 Modify your template so that the emitter re-emits when a child event occurs.
修改模板,以便在子事件发生时重新发出发射器。
<ul>
<li *ngFor="let node of tree">{{ node.name }}</li>
<button (click)="clickToEmit()">Click Me!!!</button>
<app-child [tree]="node.children" (nodeEmitter)="nodeEmitter.emit($event)"></app-child>
</ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.