【问题标题】:Angular importing FormsModule in app.module vs child.moduleAngular 在 app.module 与 child.module 中导入 FormsModule
【发布时间】:2019-03-02 09:49:59
【问题描述】:

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

但是关于FormsModule,这行不通。我必须在子模块中导入它,否则会出现以下错误:

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

你知道为什么会这样吗?

【问题讨论】:

    标签: angular angular-ngmodel


    【解决方案1】:

    我找到了答案here

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

    【讨论】:

      【解决方案2】:

      创建共享模块

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

      并将其添加到 app.module.ts

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

      【讨论】:

      • 谢谢。您的解决方案似乎很好。但我需要知道为什么会在 FormsModule 而不是 HttpClient 模块中发生这种情况。
      • 找到了答案。谢谢。
      猜你喜欢
      • 2017-03-13
      • 2020-07-11
      • 2018-10-20
      • 1970-01-01
      • 2017-02-10
      • 1970-01-01
      • 2017-01-25
      • 2018-04-11
      相关资源
      最近更新 更多