简体   繁体   English

导入 Angular 功能模块时渲染组件

[英]Render a Component when a Angular Feature module is imported

I have an Angular Application.我有一个 Angular 应用程序。 In my app.module.ts declaration I would do something like this:在我的app.module.ts声明中,我会做这样的事情:

App.module (my Root Module): App.module(我的根模块):

let imports = [
     //....
];
if (!environment.production) {
   imports.push(DevToolsModule);
} 

@NgModule({
  imports: imports,
  ...
  })

DevToolsModule (my Feature Module): DevToolsModule(我的功能模块):

My separate feature module DevToolsModule looks like the following:我的独立功能模块DevToolsModule如下所示:

@NgModule({
  declarations: [DeveloperToolsComponent],
  imports: [
    CommonModule
  ],
  entryComponents: [DeveloperToolsComponent]
})
export class DevToolsModule {}

What I would do now, is the following:我现在要做的是:

When my DevToolsModule gets imported, I would like to show a component on my screen with some developer information.当我的DevToolsModule被导入时,我想在我的屏幕上显示一个包含一些开发人员信息的组件。 It should be automatically added, I don't want to define it anywhere in my app.html template.它应该是自动添加的,我不想在我的app.html模板中的任何地方定义它。

Did anyone achieve something like that?有没有人取得这样的成就?

Thanks so much, Sebastian非常感谢,塞巴斯蒂安

You can do the following,您可以执行以下操作,

    let developmentModules = [ 
         DevToolsModule
     ] 
     if(environment.production) {
        developmentModules = [];
        enableProdMode();
     }
     @NgModule({
       imports: [
         BrowserModule,
         ...developmentModules
       ],
       declarations: [],
       providers: [],
     })
     export class AppModule

The spread operator ... allows to easily place an expanded version of an array into another array.扩展运算符...允许轻松地将扩展版本的数组放入另一个数组中。

When you import your feature module in root module, it will automatically be added to tree.当您在根模块中导入功能模块时,它将自动添加到树中。 You don't need to edit app.component.html template for that, but to demonstration, you should.您不需要为此编辑 app.component.html 模板,但为了演示,您应该这样做。 If you can't edit app.component.html template, you can add the feature module component dynamically as @viewchild instance and ComponentFactoryResolver in app.component.ts, but I wouldn't recommend it.如果您无法编辑 app.component.html 模板,您可以将功能模块组件动态添加为 app.component.ts 中的@viewchild 实例和 ComponentFactoryResolver,但我不建议这样做。 Instead you should define the feature module component as a decleration, then use it in template相反,您应该将功能模块组件定义为声明,然后在模板中使用它

<child-component></child-component>

Anyway if you still find this silly, you might want checkout the article: Dynamically add components to the DOM with Angular无论如何,如果您仍然觉得这很愚蠢,您可能需要查看文章: Dynamically add components to the DOM with Angular

Theoretically thinking of this:理论上这样想:

constructor(@Optional() devToolsModule:DevToolsModule ) {
    if(devToolsModule){
       //add component to view
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM