使用createComponent创建子组件时如何获取子组件内的变量
Angular动态创建组件实现子向父传数据方案
你通过createComponent创建组件返回的是ComponentRef实例,可直接通过该实例访问子组件属性、订阅子组件事件,不需要在模板里绑定选择器,具体实现分两种场景:
场景1:子组件数据更新时实时推送给父组件
- 先在子组件
TextlibreComponent中声明输出事件,以及公开的内部数据属性:
import { Component, EventEmitter, Output } from '@angular/core'; @Component({ // 你原有的组件配置 }) export class TextlibreComponent { // 组件内部的对象数组 objectArray: any[] = []; // 用于向父组件传值的输出事件 @Output() arrayChange = new EventEmitter<any[]>(); // 内部数组更新、需要通知父组件时调用该方法 onArrayUpdate() { this.arrayChange.emit(this.objectArray); } }
- 在父组件动态创建组件的逻辑中,拿到组件实例订阅事件即可:
TextLibre() { const cnp = this.componentFactoryResolver.resolveComponentFactory(TextlibreComponent); const view = this.viewContainerRef.createComponent(cnp); // 拿到子组件实例,订阅传值事件 const childComp = view.instance as TextlibreComponent; childComp.arrayChange.subscribe((data) => { // 此处即可拿到子组件传过来的对象数组,做对应业务处理 console.log('收到子组件数据:', data); }); this.viewList.push(view); this.SetLocation(); }
场景2:父组件主动在特定时机拉取所有子组件数据
如果不需要实时推送,只需要在比如点击提交按钮时统一收集所有动态创建的子组件数据,直接遍历你存储的viewList即可:
// 比如点击保存时调用该方法收集所有子组件数据 collectAllChildData() { const allChildArray = []; this.viewList.forEach(viewRef => { const childComp = viewRef.instance as TextlibreComponent; // 直接访问子组件上公开的对象数组属性 allChildArray.push(childComp.objectArray); }); // 后续处理收集到的全量子组件数据即可 }
- 注意事项:如果订阅了子组件的事件,记得在组件销毁时取消订阅,避免内存泄漏。动态创建的组件无法通过
@ViewChild查询获取,直接通过createComponent返回的ComponentRef访问实例是官方推荐的标准方式。
内容的提问来源于stack exchange,提问作者Pierre Laurent
相关产品推荐
相关产品推荐

