Angular 在 app.module 与 child.module 中导入 FormsModule

Angular importing FormsModule in app.module vs child.module

我正在使用 Angular 延迟加载模块。每个组件都有自己的模块。如果我在根模块 (app.module) 中导入一个模块,它一定能正常工作。比如我在app.module中导入了HttpClientModule,可以在子组件中使用。

但是大约 FormsModule,这不能正常工作。我必须在子模块中导入它,否则会出现以下错误:

Can't bind to 'ngModel' since it isn't a known property of 'input'. ("

你知道为什么会这样吗?

创建共享模块

@NgModule({

 imports: [
    CommonModule,
    FormsModule,
  ],
  declarations: [
  ],
  exports: [
    CommonModule,
    FormsModule,
  ]
})
export class SharedModule {
}

并将其添加到 app.module.ts

 imports: [ SharedModule.forRoot(),
// Core Module
CoreModule.forRoot()]

我找到了答案here:

  • 如果模块是为组件导入的,则需要在每个需要它们的模块中导入它,
  • 如果模块是为服务导入的,您只需在第一个应用模块中导入一次。