繁体   English   中英

当父组件不使用子组件选择器时,如何将数据从子组件传递到Angular6中的父组件?

[英]How to pass data from child to parent component in Angular6 when parent component not using child's component selector?

我使用ViewContainerRef动态地将子组件添加到父组件,因此不在父选择器模板或html中使用子选择器。

在这种情况下,如何将数据从子组件传递到父组件?

所以基本上让我们假设您有:

子组件

export class ChildComponent {
   ...
   outputData: EventEmitter<any> = new EventEmitter<any>();
   ...

   triggerChange() {
      // here you just emit some data using event emitter
      this.outputData.emit(someData);
   }
}

然后,在父组件中,您可以像这样从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);
   }
}

希望能有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM