【发布时间】:2018-11-03 19:12:24
【问题描述】:
我编写了以下代码,我在其中循环组件以显示子项
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
<app-child [tree]="tree" (nodeEmitter)="nodeClicked($event)"></app-child>
child.component.ts
@Input() tree;
@Output() nodeEmitter = new EventEmitter();
clickToEmit() {
this.nodeEmitter.emit(1);
}
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>
这里,我的问题是
我能够在 parent.component.html
中获得发出的事件
我无法将发出的事件从 child.component.html 获取到
parent.component.html
我收到错误,因为 nodeClicked 未在 child.component.ts
中定义我在这里做错了什么?我在这个问题上浪费了很多时间。
感谢您的帮助... :-)
【问题讨论】:
-
你的 child.component.html 中不需要这个
<app-child [tree]="node.children" (nodeEmitter)="nodeClicked($event)"></app-child> -
并且您收到该错误,因为 nodeClicked() 函数未在 child.component.ts 中定义
-
那我怎样才能从子子子中获取发出的事件数据呢?能不能给个答案,没看懂。对不起!!!
-
@TeddySterne 在他的回答中已经提到过,您可以查看。谢谢
标签: javascript angular typescript components angular2-directives