[英]angular2 emit event from dynamic child to parent
我在父模板中有子元素。 孩子是动态添加的。 从孩子我想调用父母函数,它添加了另一个孩子。 我为此使用@Output
,它可以工作,当孩子是静态的,但浏览器无法编译页面,当孩子被动态添加时:
家长:
@ViewChild('dragdrophost', {
read: ViewContainerRef
})
viewContainerRef: ViewContainerRef;
loadDragDropComponent() {
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(
DragDropComponent
);
let componentRef = this.viewContainerRef.createComponent(componentFactory);
}
父 HTML:
<div *ngIf="repair_picture" fxLayoutAlign.xs="center" fxLayoutWrap="wrap">
<!-- static works -->
<pd-drag-drop (loadComponent)="loadDragDropComponent($event)"></pd-drag-drop>
<!-- dynamic does not works-->
<ng-template #dragdrophost (loadComponent)="loadDragDropComponent($event)"></ng-template>
</div>
孩子:
export class DragDropComponent implements OnInit {
@Output() loadComponent = new EventEmitter<string>();
......
this.loadComponent.emit('loadComponent');
}
Compiler error:
Event binding loadComponent not emitted by any directive on an embedded template. Make sure that the event name is spelled correctly and all directives are listed in the "@NgModule.declarations". ("eady shown, it is possible to dynamically load component-->
<ng-template #dragdrophost [ERROR ->](loadComponent)="loadDragDropComponent($event)"></ng-template>
由于您正在动态创建组件,因此您需要连接任何活动以传递输入并监听输出。 要在您的情况下连接输出,您只需要另一行来连接监听事件:
loadDragDropComponent() {
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(
DragDropComponent
);
let componentRef = this.viewContainerRef.createComponent(componentFactory);
componentRef.instance.loadComponent.subscribe($event => {
this.loadDragDropComponent($event)
});
}
您还需要删除模板中连接侦听器的内容,因为它无效(即(loadComponent)="loadDragDropComponent($event)"
)。
您需要在新组件中传递一些回调函数。
let componentRef = this.viewContainerRef.createComponent(componentFactory);
componentRef.instance.loadComponent = function() {
// put your code here
}
然后你可以在组件内部调用你的回调
this.loadComponent();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.