【问题标题】:Angular 2 can no longer import components into other components with modulesAngular 2 不能再将组件导入到其他带有模块的组件中
【发布时间】:2023-03-11 06:00:01
【问题描述】:

我最近重新构建了我的架构,并为每个组件创建了模块,这样我就可以在路由时延迟加载它们。这很好用。但是,我现在只是将组件导入其他组件时遇到了问题,并且不完全确定原因。我是这样导入的:

import {TrackingComponent} from './tracking/tracking.component';

我的选择器很简单:

<tracking></tracking>

当我运行它时,我得到:

error_handler.js:46 例外:未捕获(在承诺中):错误:模板解析错误: “跟踪”不是已知元素:

知道我做错了什么吗?目前,模块/组件的区别有点模糊。谢谢。

【问题讨论】:

  • 你能更新你的 TrackingComponent 吗?

标签: angular angular2-routing


【解决方案1】:

您不需要将组件类导入其他类。这绝对没有任何作用(在 Angular 的上下文中),但让您可以在另一个文件中使用该类。

您需要做的是@NgModule.imports 组件所在的任何模块,进入您尝试使用其他组件的组件的另一个模块

@Component({
  selector: 'other'
})
class OtherComponent {}

@NgModule({
  declarations: [ OtherComponent ],
  exports: [ OtherComponent ]
})
class OtherModule {}

@Component({
  selector: 'consumer',
  template: '<other></other>'
})
class ConsumerComponent {}

@NgModule({
  imports: [ OtherModule ],
  declarations: [ CosumerComponent ],
  exports: [ ConsumerComponent ]
})
class ConsumerModule {}

【讨论】:

  • 谢谢,这似乎有效。这很奇怪,因为我已经将我的 Nav 组件导入到另一个没有模块的组件中,并且效果很好,而不是求助于使用模块。
  • 如果组件在同一个模块中声明,那么它可以工作。这就是它的样子。如果组件在不同的模块中声明,则需要将该模块导入到目标组件所在的模块中。
猜你喜欢
  • 2018-07-13
  • 1970-01-01
  • 2019-05-29
  • 1970-01-01
  • 2018-11-20
  • 2017-06-23
  • 2018-09-14
  • 2020-01-28
  • 2019-10-02
相关资源
最近更新 更多