Angular 9中如何从ViewContainerRef获取子组件?
获取ViewContainerRef中动态组件的实例
你遇到的问题很常见——ViewContainerRef.get(index)返回的是组件的宿主视图(ViewRef),而不是组件实例本身。这里有两种可靠的方法来获取你需要的SimpleCardComponent实例:
方法1:存储创建时的ComponentRef(推荐)
最稳妥的方式是在创建动态组件时,把返回的ComponentRef存入一个数组中,后续直接从数组里获取实例,不需要从ViewRef反向推导:
// 先定义数组保存所有组件引用 private cardComponentRefs: ComponentRef<SimpleCardComponent>[] = []; // 创建组件时将引用存入数组 const componentFactory = this.resolver.resolveComponentFactory(SimpleCardComponent); const componentRef = this.cards_holder.createComponent(componentFactory); this.cardComponentRefs.push(componentRef); // 后续遍历获取组件实例 this.cardComponentRefs.forEach(ref => { console.log(ref.instance); // 这就是你要的SimpleCardComponent实例 });
这种方法的优势是类型安全,而且避免了后续从ViewRef中提取实例可能出现的意外问题,比如当容器中混合了组件和嵌入式模板视图时。
方法2:从ViewRef中提取组件实例
如果你不想额外存储引用,可以通过ViewRef的注入器(Injector)来获取组件实例:
for (let index = 0; index < this.cards_holder.length; index++) { const viewRef = this.cards_holder.get(index); // 通过injector直接获取组件实例 const cardInstance = viewRef.injector.get(SimpleCardComponent); console.log(cardInstance); // 得到SimpleCardComponent实例 }
原理是每个组件的视图都关联着自己的注入器,通过注入器可以直接获取到组件的实例对象。需要注意的是,如果你的ViewContainerRef中同时存在组件视图和嵌入式模板视图(比如用createEmbeddedView创建的),这种方法可能会报错,所以确保容器中只有你创建的SimpleCardComponent视图时再使用。
内容的提问来源于stack exchange,提问作者Sabish.M
相关产品推荐
相关产品推荐

