【问题标题】:Angular exported component from module not useable in another module从模块中导出的角度组件在另一个模块中不可用
【发布时间】:2018-03-05 00:53:51
【问题描述】:

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

我正在尝试在 TestModule 的一个组件中使用 CalendarComponent 和选择器“app-calendar”。

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”不是已知元素(不是模块的一部分)的错误

我错过了什么?

【问题讨论】:

  • TestModule 应该导入正在导出日历组件的模块
  • @yurzui AppModule 已经导入了 TestModule,所以 TestModule 无法导入 AppModule,因为那将是循环依赖还是我错了?
  • 是的,你是对的
  • 你应该在游览页面的模块中导入calendarComponent的模块

标签: angular angular-components angular-module


【解决方案1】:

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

calendar.module.ts

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

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

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 {}

更多详情见

【讨论】:

    猜你喜欢
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    相关资源
    最近更新 更多