简体   繁体   English

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

[英]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: 所以基本上让我们假设您有:

Child component 子组件

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访问数据:

Parent component 父组件

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.

相关问题 Angular6创建模板并将模板从父组件传递给子组件 - Angular6 create and pass a template from a parent component to a child 如何在Angular4中将数据从子组件传递到父组件 - How to pass data from child component to parent component in Angular4 如何以角度将数据从父组件传递到自动完成子组件 - How to Pass data to autocomplete child component from parent component in angular 如何将角度5中的点击数据从父组件传递到子组件? - How to pass data on click in angular 5 from parent component to child component? Angular:如何将数据从父组件传递到子组件? - Angular : How to pass data from parent component to child component? angular中如何将数据从父组件传回子组件 - How to pass back data from parent component to child component in angular 如何从父组件向子组件传递数据 angular 14 - How to pass data from parent component to child component angular 14 Angular6-初始化父级时如何初始化子级组件? - Angular6 - How to initialize child component when parent is initialized? Angular Parent Child - 将数据传递给子组件 - Angular Parent Child - Pass data to child component 如果子组件为动态组件,如何将数据从子组件传递给父组件 - How to pass data from Child to Parent, if Child component dynamic component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM