angular2 rc5使用功能模块中的组件无法正常工作

时间:2016-08-22 00:27:46

标签: angularjs angular typescript angular2-components angular2-ngmodel

我有一个app模块和一个功能模块。名为“AudioPlayerComponent”的组件在功能模块中声明。我想在app模块中使用它,但它没有显示。没有错误。

我错过了什么吗?

应用模块:

@NgModule({
  imports: [
    BrowserModule,
    HomeModule, 
    ReciterModule, // the feature module which has the audio player
    routing
  ],
  declarations: [
    AppComponent,
    NavComponent
  ],
  providers: [
    appRoutingProviders,
    AudioPlayerService
  ],
  bootstrap: [AppComponent]
})

功能模块:

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    HttpModule,
    reciterRouting
  ],
  declarations: [
    ReciterDetailComponent, 
    WidgetComponent,
    AudioPlayerComponent  // this is the component I want to also use in the app component
  ],
  providers: [
    AppService,
    RecitersService 
  ]
}) 

功能模块中使用音频播放器(显示)的组件

<div class="reciter-detail">
   ...
    <audio-player></audio-player>

</div>

试图使用音频播放器的应用程序组件(未显示):

<nav-main></nav-main> 
 <div class="container">

    <router-outlet></router-outlet>


    <audio-player></audio-player>
</div>

2 个答案:

答案 0 :(得分:4)

您必须在功能模块的导出中添加AudioPlayerComponent

如果您想使用功能模块中的任何组件,管道,指令到另一个模块,您需要将它们导出

  @NgModule({
   imports: [
     CommonModule,
     FormsModule,
     HttpModule,
     reciterRouting
    ],
   declarations: [
     ReciterDetailComponent, 
     WidgetComponent,
     AudioPlayerComponent  // this is the component I want to also use in the app component
   ],
   //add exports
   exports: [ 
      AudioPlayerComponent
   ],
   providers: [
     AppService,
     RecitersService 
   ]
  }) 

详细了解NgModule属性here

希望这会有所帮助!!

答案 1 :(得分:0)

接受的答案是正确的。我结束阅读指南并制作一个单独的共享模块。

共享模块:

@NgModule({
    imports: [CommonModule],
    declarations: [
        AudioPlayerComponent
    ],
    exports: [ 
        AudioPlayerComponent,
        CommonModule,
        FormsModule
    ]
})
export class SharedModule {
    static forRoot(): ModuleWithProviders {
        return {
            ngModule: SharedModule,
            providers: [AppService,AudioPlayerService]
        };
    }
}

应用模块

@NgModule({
  imports: [
    BrowserModule,
    HomeModule, 
    ReciterModule,
    routing, 
    SharedModule.forRoot()
  ],
  declarations: [
    AppComponent,
    NavComponent
  ],
  providers: [
    appRoutingProviders 
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

功能模块

@NgModule({
  imports: [ 
    HttpModule,
    reciterRouting,
    SharedModule
  ],
  declarations: [
    ReciterDetailComponent, 
    WidgetComponent 
  ],
  providers: [ 
    RecitersService 
  ],
  exports: [ReciterDetailComponent]
})