我在父模板中具有子元素。动态添加孩子。我想打电话给父母功能,这增加了另一个孩子。我对此使用@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();