问题出现的原因是动态组件内部的子组件没有被正确渲染。解决方法是在动态组件内部添加一个
元素,然后在该元素内部插入子组件的选择器。
示例代码:
// 父组件中动态创建子组件的函数 createDynamicComponent(){ const componentFactory = this.componentFactoryResolver.resolveComponentFactory(MyDynamicComponent); const componentRef = this.dynamicComponentContainer.createComponent(componentFactory); // 插入选择器,将子组件渲染出来 const childComponentElement = componentRef.instance.viewContainerRef; childComponentElement.createEmbeddedView(this.templateRef); }
// 在子组件中添加 ng-container 元素,用于渲染子组件
// 父组件中使用结构指令插入子组件的选择器
上一篇:Angular动态字符串绑定