[英]How to pass data from child to parent component in Angular6 when parent component not using child's component selector?
I am adding a child component to a parent component dynamically using ViewContainerRef
so not using child selector in parent selector template or in html. 我使用
ViewContainerRef
动态地将子组件添加到父组件,因此不在父选择器模板或html中使用子选择器。
How to pass data from child to parent component in this case? 在这种情况下,如何将数据从子组件传递到父组件?
So basically let's suppose that you have: 所以基本上让我们假设您有:
export class ChildComponent {
...
outputData: EventEmitter<any> = new EventEmitter<any>();
...
triggerChange() {
// here you just emit some data using event emitter
this.outputData.emit(someData);
}
}
Then in parent component you can access data from EventEmitter like: 然后,在父组件中,您可以像这样从EventEmitter访问数据:
export class ParentComponent {
attachChild() {
...
let componentRef = viewContainerRef.createComponent(componentFactory);
(<ChildComponent>componentRef.instance).outputData.subscribe(this.outputData.bind(this));
}
onDataChange(someData) {
// here you can access child's data when event emitter triggers
// so basically it's the same if you subscribed on @Output field from template like (outputData)="onDataChange($event)"
console.log(someData);
}
}
Hope that helps. 希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.