我的所有事件 Launcher 都正常工作,除了一个 .
child.ts:
@Component({
...
outputs: ['fileUploaded']
})
export class childComponent implements OnInit {
...
fileUploaded = new EventEmitter<boolean>();
...
randomMethod(){
...
this.fileUploaded.emit(true);
}
}
从父组件调用randomMethod(),我将在parent.ts中显示 . 它不是在child.html中调用的 .
parent.html
...
<child (fileUploaded)="onSubmit($event)"></child>
..
parent.ts
export class parentComponent {
...
theChild = new childComponent;
submitted = false;
...
onSubmit(event: boolean) {
console.log('in onSubmit()');
this.submitted = event;
}
functionCallsChild(){
this.theChild.randomMethod();
...
this.theChild = new childComponent;
}
}
我的应用程序从不记录“inSubmit()”,为什么不调用此方法?我也尝试不在我的最后一行创建一个新的子对象,但这没有什么区别 .
5 回答
您可以使用@Output Launcher 从子组件调用父组件的方法,该 Launcher 将触发子组件上的任何事件 . 我在评论部分使用这种方法来使用子组件的方法更新父组件中的计数 .
Parent.ts
Parent.HTML
Child.ts
在全局范围内,您可以在子组件中声明@Output事件,即child.ts
您不应该使用new运算符创建子组件 .
您应该使用
@ViewChild()
来引用子组件 .试试这种方式:
并删除:
检查文档here! :d
也许我没有't clear why you choose this approach or what you need it for, but as far as I know, you'应该使用从孩子到其父母的
EventEmitter
. 这意味着将触发.emit()shold的事件放在child.html中 . 尝试这样做,它应该工作:child.html
child.ts:
parent.html
parent.ts
希望它有所帮助 .
您选择的子组件是错误的,您应该使用
ViewChild
这样:parent.html:
parent.ts: