使组件可用于嵌套模块

时间:2016-11-17 16:09:08

标签: angular typescript

所以现在我有一个看起来像这样的设置:

  • 应用模块
    • 大型模块
      • 另一个大型模块
        • 组件

A Component无权访问A Large Module中加载的组件,即使这些组件被定义为两个A Large Module的导出。

有什么方法可以让嵌套模块Another Large Module访问A Large Module的组件导入,这样它的子组件就可以访问这些组件了吗?或者这些是否需要在Another Large Module内声明,以便它的子组件可以访问它们?

2 个答案:

答案 0 :(得分:2)

如果在其中声明的组件使用这些内容,则需要导入模块中的内容。您可以创建一个功能模块,用于导入/导出/声明组件集,并在其他模块中使用它。

- App Module
   - FeatureA Module
   - FeatureB Module
   - Large Module (import FeatureA Module)
       - Component [can use components from FeatureA; 
                    can't use components from FeatureB]
       - Another Large Module (import FeatureA Module, FeatureB Module)
           - Component [can use components from FeatureA and FeatureB]

如果您的Large ModuleAnother Large Module延迟加载,则两个文件/包中都会有FeatureA module,但很少有额外的千字节会受到影响。一个额外的好处是可重用性,您可以在其他项目中使用功能模块:

- Different App Module
   - FeatureA Module
   - FeatureB Module
   - Different Large Module (import FeatureA Module)
       - Component [can use components from FeatureA; 
                    can't use components from FeatureB]

答案 1 :(得分:0)

如果您想在模块之间共享组件,最简单的方法是创建shared.module.ts:

const SHARED_COMPONENTS = [];

const SHARED_MODULES = [];

@NgModule({
  declarations: [
    ...SHARED_COMPONENTS
  ],
  imports: [
    ...SHARED_MODULES
  ],
  exports: [
    ...SHARED_COMPONENTS,
    ...SHARED_MODULES
  ]
})
export class SharedModule { }

注意'导出'键,它允许您在层次结构中的任何位置导入SharedModule,并使用来自各处的共享组件。

相关问题