在 Angular 中,当我想动态创建组件时,如何获取所在模块的 ngModuleRef?

问题描述 投票:0回答:1

考虑这样创建的模块:

@NgModule({
  imports: [ BrowserModule ],
  providers: [ AdService ],
  declarations: [
    AppComponent,
    AdBannerComponent,
    HeroJobAdComponent,
    HeroProfileComponent,
    AdDirective
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

我想获取 AppModule 的 ngModuleRef ,以便我可以将其作为选项参数传递给 createComponent 函数,如下所示:

viewContainerRef.createComponent<AdComponent>(addItem.component,{ngModuleRef:myModuleRef<unknown>})

这可能吗?如果是这样,我如何让 ngModuleRef 来做到这一点?

angular angular-module
1个回答
4
投票

注意:答案已于 2022 年给出,适用于 Angular v14

如果您要动态加载模块,则可以这样做。

const { AppModule } = await import(`PATH_TO_MODULE_TS`);
const ngModuleRef = createNgModuleRef(AppModule) // createNgModuleRef is from @angular/core

如果需要定义提供程序,您可以将

Injector
作为第二个参数传递给
createNgModuleRef
,或者也可以在
createComponent
方法的选项中传递注入器。

© www.soinside.com 2019 - 2024. All rights reserved.