在子模块中使用导入模块中的组件

Using component from imported module inside of child modules

我有一个导出组件以将其暴露给其他模块的模块,我想在另一个模块的子模块中使用此组件,我正在导入父模块中的第一个模块以启用在子模块,但我并不完全相信这是最好的方法。

这是我在根文件夹中的共享模块,其中包含我要使用的组件:

app/shared/shared.module.ts

import {dtComponent} from './dt.component';

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

我在 app 文件夹中有另一个导入 DatePModule 的模块,如下所示:

app/contacts/contacts.module.ts

import {DatePModule} from '../shared/shared.module.ts';

@NgModule({
  imports: [
    CommonModule,
    DatePModule
  ]
})
export class CTModule{ }

我需要在 CTModule 的某些组件中直接使用 dtComponent,但在子模块中的其他组件中也需要此组件CTModule.

我可以在 CTModule 的子模块中再次导入 DatePModule 但我不认为这是最好的方法。

app/contacts/other/other.module.ts

import {DatePModule} from '../../shared/shared.module.ts';

@NgModule({
  imports: [
    CommonModule,
    DatePModule
  ]
})
export class OtherModule{ }

我的问题是,如果 DatePModule 已经在父模块中导入,为什么我需要再次导入?如果我在 OtherModule 中删除此导入,则组件 dtComponent 不会被识别为模块的一部分。

why I need to import again DatePModule if is already imported in parent module

相互导入的模块之间没有层次结构。所有模块都与所有组件合并到一个模块定义工厂中。如果您使用延迟加载,仍然适用。懒加载模块和共享模块将被合并,它们之间将没有层次结构。

要了解更多信息,请阅读 Avoiding common confusions with modules in Angular。这是引用:

The biggest confusion regarding imports in modules is that developers think it makes a hierarchy. And it’s probably reasonable to assume that a module that imports other modules becomes the parent module for its imports. However, that’s not what happens. All modules are merged during compilation phase. And thus non-lazy loaded modules do not create any hierarchy.

但是,模块 imports/exports 可以在编译期间 强制执行可声明类型封装 。如果你想使用来自另一个模块的可声明类型,你必须显式导入这个模块或其他重新导出所需模块的模块。编译器在解析模板时控制封装,显式导入提供上下文以了解某些组件可以用作模板中的子组件。

I can do it importing again DatePModule inside of child modules of CTModule but I am not convinced that is the best approach.

如果您想在 OtherModule.

中使用来自 DatePModule 的可声明类型,这是正确的方法