当CommonModule在根模块(appmodule)中被导入和重新导出时,为什么有必要将它导入到其他自定义/子模块中



假设我有一个应用程序,有两个模块

  • AppModule
  • MyChildModule

CommonModuleAppModule进口再出口

MyChildModule导入到AppModule

app.module.ts

@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
CommonModule,
MyChildModule
],
exports:[
CommonModule
],
providers: [],
bootstrap: [AppComponent]
})

CommonModuleisNOT IMPORTEDtoMyChildModule

childModule.module.ts

@NgModule({
declarations: [
MyChildComponent,
],
imports: [
],
exports:[
MyChildComponent,
]
})

my-child-module-component.ts

export class ChildModuleComponent{
showMessage:boolean;
constructor(){
this.showMessage = true;
}
}

Child-module-component.html

<h1 *ngIf ='showMessage'> Hello World </h1>

现在的问题是,当我将childComponent添加到appComponent时,它说*ngIf不是一个已知属性。由于*ngIfcommonModule的指令,并且childModulecommonModule都导入到同一个模块,即AppModule

app.component.ts

<my-child-component></my-child-component> <!-- *it should display *Hello World text* -->

不需要在AppModule中导出

  1. 没有任何东西正在"导入App module"。
  2. 你可以在其他地方导入模块,所以没有必要在这里导出。

你需要在ChildModule中导入CommonModule,例如,从文档https://angular.io/api/common/CommonModule中,你需要*ngIf管道。

把childModule想象成一个独立的容器,在那里启动它必须有所需的一切(在这种情况下,它是请求*ngIf,即。CommonModule)

重要:一旦在模块中声明了组件,就不能在另一个模块中导入了

你想在你的例子中做什么:

@NgModule({
declarations: [
MyChildComponent,
],
imports: [
CommonModule
],
exports:[
MyChildComponent,
]
})

如果有帮助,请告诉我。