Angular importing FormsModule in app.module vs child.module

[亡魂溺海] 提交于 2020-08-08 07:07:08

问题


I'm using Angular with lazy loading modules. Each component has its own module. If I import a module in the root module (app.module) it must work fine. For example, I imported HttpClientModule in app.module and can use it in child components.

But about FormsModule, this doesn't work fine. I must import it in the child module, otherwise, I get the following errors:

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

Do you have any idea why this happens?

回答1:


I found the answer here:

  • if the module is imported for components, you’ll need to import it in each module needing them,
  • if the module is imported for services, you’ll need to import it only once, in the first app module.



回答2:


create the SharedModule

@NgModule({

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

and add this to app.module.ts

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


来源:https://stackoverflow.com/questions/54957210/angular-importing-formsmodule-in-app-module-vs-child-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!