Angular技术问题:如何导出entryComponents组件及跨模块动态使用
嘿,我来帮你搞定这两个Angular组件相关的问题~
问题1:如何导出entryComponents中的组件供其他模块使用?
首先得理清一个关键点:entryComponents 在Angular里的核心作用是告诉编译器「这个组件会被动态创建,需要提前编译好」,不过从Angular 9启用Ivy编译器之后,这个配置其实已经不是必须的了——编译器会自动识别出动态使用的组件。
要让其他模块能用上这个组件,你只需要做两步:
- 第一步:在组件所在的模块(比如你的
page.module.ts)中,把该组件添加到exports数组里。只有被导出的组件,其他模块导入该模块后才能访问到它。 - 第二步:在需要使用该组件的目标模块(比如
app.module.ts)中,导入组件所在的模块(也就是PageModule)。
如果是Angular 8及更早的版本,你还得确保组件所在模块的entryComponents数组里包含该组件,但核心的导出逻辑还是靠exports数组,entryComponents只是负责预编译的提示。
问题2:app.module中动态使用page.module里的DynamicComponent怎么配置?
看你给出的page.module.ts代码,已经把DynamicComponent加到了declarations、entryComponents和exports里,这就已经完成了导出的准备工作。那app.module.ts只需要做一件事:
在app.module.ts的imports数组中导入PageModule就行。
示例配置如下:
@NgModule({ declarations: [AppComponent, ...], imports: [ BrowserModule, PageModule, // 导入包含DynamicComponent的PageModule ... ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
之后在app模块的组件里动态创建DynamicComponent时,就可以用ComponentFactoryResolver配合ViewContainerRef来实现,给你个简单的示例代码:
import { Component, ComponentFactoryResolver, ViewContainerRef, ViewChild } from '@angular/core'; import { DynamicComponent } from '../path/to/dynamic.component'; // 注意路径要正确 @Component({ selector: 'app-root', template: '<div #container></div>' }) export class AppComponent { @ViewChild('container', { read: ViewContainerRef }) private container!: ViewContainerRef; constructor(private resolver: ComponentFactoryResolver) {} ngOnInit() { const componentFactory = this.resolver.resolveComponentFactory(DynamicComponent); this.container.createComponent(componentFactory); } }
另外提一句,如果你用的是Angular 9+的Ivy编译器,page.module.ts里的entryComponents其实可以删掉了,编译器会自动处理动态组件的预编译工作。
内容的提问来源于stack exchange,提问作者Eimard
相关产品推荐
相关产品推荐

