Angular 中使用module中component的一个坑

本文记录了在Angular项目中,如何解决在product-list模块中导入shared模块的star组件时遇到的错误,涉及 NgModule 的正确导入和组件引用的注意事项。作者通过逐步排查和对比发现,app.module 必须导入引用了 SharedModule 的 ProductModule 才能正常工作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在一个module中使用另一个module的componet

最近在使用Angular做一个项目,之前对于angular的接触不多,所以使用过程中碰到了一些坑,在此记录其中一个

error

先上报错信息:

Error: src/app/product/product-list/product-list.component.html:2:1 - error NG8001: 'app-star' is not a known element:
1. If 'app-star' is an Angular component, then verify that it is part of this module.
2. If 'app-star' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

下面详细解释错误的产生和解决方案

需求

一个很简单的需求,希望在product-list component (属于product module)中使用shared module中的star component. 工程目录app下的结构如下:

app
│  app-routing.module.ts
│  app.component.css
│  app.component.html
│  app.component.spec.ts
│  app.component.ts
│  app.module.ts
│
├─products
│      product-list.component.css
│      product-list.component.html
│      product-list.component.spec.ts
│      product-list.component.ts
│      products.module.ts
│
└─shared
        shared.module.ts
        star.component.css
        star.component.html
        star.component.spec.ts
        star.component.ts

创建过程

创建工程的步骤如下:

ng n mouduletest  //接下来的Add routing选Y,stylesheet 选CSS
ng g m products
ng g c products/product-list --flat
ng g m shared
ng g c shared/star --flat

在app-routing-module中增加路径定义并增加import:

import { ProductListComponent } from './product/product-list/product-list.component';
const routes: Routes = [
  {path:'',component:ProductListComponent}
];

这时候如果ng serve 是没有问题的,能够显示product-list works!

引入star component

在shared module 中export star component .
将shared.module中@NgModule声明中增加:

  exports:[
    StarComponent
  ]

然后在product-list module中import star module
在product.module的@NgModule声明中imports中增加SharedModule:

  imports: [
    CommonModule,
    SharedModule
  ],

再在product-list.componet.html中增加对star的引用。
增加:

<app-star></app-star>

这时候ng serve,报错了,错误内容就是开头的内容。

查找问题

经过了多方搜索,搜到结果最多的就是要在shared.module中增加exports,可是这个我已经做了。

转机

后来看了一个课程里面讲module,里面用到的结构跟我用到的差不多,但是是可以工作的,按照里面的命令和操作抄了一遍,居然能工作。

查找问题

下面的工作就变成了查看这两个工程的差异了,我按照无限接近的方式生成了一系列的工程,按照创建过程中的步骤把工程做的无限接近成功的工程。发现还是报错。
然后拿出beyond compare比较两个文件夹中的内容。最终发现了端倪。
成功的工程中app.module中@NgModule的imports中多了一行ProductModule.

然后我在之前error的工程中都照此加上,成功了。

总结一下

我感觉非常诡异的一点,app.module中没有import ProductModule,如果ProductModule中不引用其他module,那么能够正常使用,可是如果ProductModule中引用了SharedModule,那么就必须在appModule中引用 ProductModule,让我感到非常诡异,没有理解其中的逻辑,但是不管怎样,终于找到了问题。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值