当通过ng-template呈现子元素时,将数据从子元素传递给父元素



我使用@ViewChild通过模板引用变量创建子组件。我想传递数据从动态创建的子到它的父,以任何方式,但最好使用@Output装饰器。

这有可能吗?

Parent.html

<ng-template #childComponent></ng-template>

Parent.ts

@ViewChild("childComponent", { static: true, read: ViewContainerRef })
myChildComponent: ViewContainerRef;
componentRef: ComponentRef<any>;
createComponent() {
const myChildComponentRef = this.myChildComponent;
this.componentRef = myChildComponentRef.createComponent(ChildComponent);
this.componentRef.changeDetectorRef.detectChanges();

Child.html

<div class="table-container">
Some table here, populated by data from a server response
</div>

Child.ts

@Output() data = new EventEmitter<any[]>();
constructor() { }
outputData() {
this.data.emit(serverResponse);
}

我以前使用过@Output,我知道父方法应该绑定到子事件,在父模板中的子选择器内。因为ng-template的关系,我没有子节点的选择器,所以我想不出一个好的方法来实现它。

事件发射器只是美化了的可观察对象。

创建子组件时,可以调用

this.componentRef.data.subscribe(...);

也不要忘记取消订阅以避免内存泄漏!

最新更新