如何在angular2中的子模块组件中使用父模块组件

j d*_*eep 15 components angular2-template angular

我有标题,应该在子模块和父模块中使用.这是在父模块中导入和使用但是当尝试导入和使用子组件时它显示错误.我的意思是如何使用父模块和子模块的公共标头

未捕获(承诺):错误:

类型HeaderComponent是2个模块的声明的一部分:AppModule和ProviderModule!请考虑将HeaderComponent移动到导入AppModule和ProviderModule的更高模块.

您还可以创建一个新的NgModule,它导出并包含HeaderComponent,然后在AppModule和ProviderModule中导入该NgModule.

ST7*_*ST7 23

您应该使用要使用的组件创建共享模块,导出这些组件,并在其他模块中导入共享模块(对于您的案例,可以导入父模块和子模块).

共享模块:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedComponent1 } from "./SharedComponent1";
import { SharedComponent2 } from "./SharedComponent2";

@NgModule({
imports: [
    CommonModule
],
declarations: [
    SharedComponent1,
    SharedComponent2
],
exports: [
    SharedComponent1,
    SharedComponent2
]
})
export class SharedModule {}
Run Code Online (Sandbox Code Playgroud)

使用共享模块:

import { NgModule }       from '@angular/core';
import { CommonModule }   from '@angular/common';
...
import { SharedModule } from './SharedModule';

@NgModule({
imports: [
    CommonModule,
    ...
    SharedModule
],
declarations: [
    ...
],
providers: [
    ...
]
})
export class AppModule{}
Run Code Online (Sandbox Code Playgroud)

  • 我认为这是一个 Angular 缺陷,这让我想完全避免使用父模块和子模块,而只使用常规模块,这样我就可以导入我需要的任何内容。父子模块到底有什么意义呢?路由?无论如何,我们应该有单独的路由模块。即便如此,将模块结构耦合到路由结构似乎是一个坏主意。你不能重复使用任何东西。 (2认同)

Pau*_*aul 7

我修改了ST7的答案。

您应该导出要在子模块中使用的父模块的组件。然后在子模块中导入父模块。

父模块(导出共享组件):

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedComponent1 } from "./SharedComponent1";
import { SharedComponent2 } from "./SharedComponent2";

@NgModule({
imports: [
    CommonModule
],
declarations: [
    SharedComponent1,
    SharedComponent2,
    ...
],
exports: [
    SharedComponent1,
    SharedComponent2
]
})
export class ParentModule {}
Run Code Online (Sandbox Code Playgroud)

子模块(导入父模块):

import { NgModule }       from '@angular/core';
import { CommonModule }   from '@angular/common';
...
import { ParentModule } from '../ParentModule';

@NgModule({
imports: [
    CommonModule,
    ...
    ParentModule
],
declarations: [
    ...
],
providers: [
    ...
]
})
export class ChildModule{}
Run Code Online (Sandbox Code Playgroud)