[英]How can I access child components values from a parent component when they are added dynamically?
[英]In Angular 5, how to get access to dynamically added child components from parent component?
我正在开发一个 Ionic + Angular 5 项目。
我需要动态加载一些组件。 按照 Angular 文档中的动态组件加载器示例,我能够成功加载组件并显示它们。
但是,我需要能够遍历加载的组件。
在创建和销毁子组件时,我可以轻松地在父组件中维护自己的组件列表,但在我看来,这很丑陋,而不是“角度方式”。
经过大量实验和研究,似乎我无法使用 @ViewChildren 访问动态添加的组件,因为它们有自己的视图。 ViewChildren 未找到动态组件
这样对吗?
我可以使用 viewContainerRef.get() 遍历子视图并检索 ViewRefs。 但是似乎没有办法在给定 ViewRef 的情况下获得对组件的引用?
我注意到 ViewRef 的“rootNodes”属性,但是该属性没有记录在 Angular 文档视图参考中。但是,它记录在 EmbeddedViewRef 文档嵌入式视图参考中,但似乎仍然没有让我访问组件。
所以问题是当我有一个动态添加子组件的父级时,我如何从父级循环到子级组件(这样我就可以在子级中调用我的方法之一)? 我怀疑是我遗漏了一些愚蠢的简单东西,有一些根本的误解,或者我应该使用不同的模式。
我修改了 Dynamic Component Loader 示例以突出显示我正在尝试做的事情。 修改后的动态组件加载器
所以,我想到了这一点,一个干净的方法(在我看来)是在父组件上传递 create 一个属性,例如parentContext
并将数据或方法传递给这个对象。
示例 - 在父组件中,您甚至可以将方法传递给子组件,它会在父组件的上下文中运行。 :
gotoDetail(hero: Hero): void {
this.entry.clear();
const factory = this.resolver.resolveComponentFactory(DynamicModalChildComponent);
this.dynamicModalComponentRef = this.entry.createComponent(factory);
this.dynamicModalComponentRef.instance.hero = hero;
// Pass parent context to child in order to close modal hierarchically (parent/child component relationship).
// This approach is less verbose and makes it easier to unit test than a service in my opinion.
this.dynamicModalComponentRef.instance.parentContext = () => this.destroyComponent();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.