来自模块的Angular导出组件在另一个模块中不可用

时间:2017-09-23 16:18:52

标签: angular angular-components angular-module

我正在AppModule中导出自定义组件,但不能在另一个模块中使用它,该模块正在AppModule中导入。我以为导出的组件是全局可见的?

我正在尝试在TestModule中的组件中使用带有选择器'app-calendar'的CalendarComponent。

app.module.ts

@NgModule({
  declarations: [ ... ,
    CalendarComponent,
  ],
  imports: [ ... ,
    TestModule,
  ],
  exports: [ ...
    CalendarComponent,
  ],
  providers: [ ... ],
  bootstrap: [AppComponent]
})

test.module.ts

@NgModule({
  declarations: [ ... ,
    TestComponent
  ],
  imports: [ ... ],
  exports: [ ... ],
  providers: [ ... ]
})

test.component.html

<app-calendar></app-calendar>

控制台抛出'app-calendar'不是已知元素(不是模块的一部分)的错误

我错过了什么?

1 个答案:

答案 0 :(得分:3)

创建CalendarModule或将Calendar组件添加到您的共享模块(取决于您的架构),例如:

calendar.module.ts

@NgModule({
  declarations: [CalendarComponent],
  exports: [CalendarComponent]
})
export class CalendarModule {}

AppModule中删除CalendarComponent,并导入CalendarModule(或SharedModule),如果某些声明使用CalendarComponent

<强> app.module.ts

@NgModule({
  declarations: [ ... ,
    CalendarComponent,  <== remove it
  ],
  imports: [
    TestModule,
    // import CalendarModule here if any of declarations above 
       use CalendarComponent in their template
  ],
  exports: [ ...
    CalendarComponent,  // remove it
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

<强> test.module.ts

@NgModule({
  declarations: [ ... ,
    TestComponent
  ],
  imports: [ 
    CalendarModule <=== add this, so TestComponent will be able 
                        to use CalenderComponent in its template
  ]
})
export class TestModule {}

有关详细信息,请参阅