我试图在其他模块中使用我在AppModule中创建的组件。我得到以下错误:

Uncaught (in promise):错误:模板解析错误 'contacts-box'不是已知元素: 如果'contacts-box'是一个Angular组件,那么验证它是否是这个模块的一部分。 如果'contacts-box'是一个Web组件,那么在'@NgModule '中添加'CUSTOM_ELEMENTS_SCHEMA'。模式来抑制此消息。

我的项目结构很简单:

我将页面保存在pages目录中,其中每个页面保存在不同的模块中(例如customers-module),每个模块都有多个组件(例如customers-list-component, customers-add-component等)。我想在这些组件中使用我的ContactBoxComponent(例如在customers-add-component内部)。

As you can see I created the contacts-box component inside the widgets directory so it's basically inside the AppModule. I added the ContactBoxComponent import to app.module.ts and put it in declarations list of AppModule. It didin't work so I googled my problem and added ContactBoxComponent to export list as well. Didn't help. I also tried putting ContactBoxComponent in CustomersAddComponent and then in another one (from different module) but I got an error saying there are multiple declarations.

我错过了什么?


当前回答

在我的例子中,问题是模块中缺少组件声明,但即使添加了声明,错误仍然存在。我不得不停止服务器并在VS Code中重新构建整个项目以消除错误。

其他回答

我有相同的问题宽度php风暴版本2017.3。这为我解决它: Intellij支持论坛

它是一个错误宽度@angular语言服务: https://www.npmjs.com/package/@angular/language-service

我也有同样的问题。在尝试这里发布的一些解决方案之前,您可能需要检查组件是否真的不能工作。对我来说,这个错误显示在我的IDE (WebStorm)中,但当我在浏览器中运行它时,结果证明代码完美地工作了。

在我关闭终端(正在运行ng serve)并重新启动IDE之后,该消息停止显示。

在执行Angular的入门教程时,我也在使用stackblitz.com工具使用Angular生成器生成一个名为product-alerts的新组件后收到了这个错误。

'app-product-alerts'不是已知元素:

发现:其他人在2021年8月初也经历过这种情况。目前,它似乎是StackBlitz IDE中的一个bug。 https://github.com/angular/angular/issues/43020

我的情况有点不同。我得到了这个错误消息,但这是因为我的页面模块没有我生成的新页面。

我的步骤:

生成新的页面组件 将现有组件导入到新页面的模块中。ts文件 在新页面的HTML文件中使用<myapp-header></myapp-header>组件选择器

得到了错误,被困在这里。对我来说,最后一步是:

导入新的页面模块到pages.module.ts文件中。

现在它按预期工作了。这次错误消息没有太大帮助。

很多答案/注释提到了在其他模块中定义的组件,或者你必须在它/它们的包含模块中导入/声明组件(你想在另一个组件中使用)。

但在简单的情况下,当组件B和组件A都定义在同一个模块中时,你必须在包含组件的模块中声明两个组件,以便B看到A,而不仅仅是A。

例如,在my-module.module.ts中

import { AComponent } from "./A/A.component";
import { BComponent } from "./B/B.component";

@NgModule({
  declarations: [
    AComponent,   // This is the one that we naturally think of adding ..
    BComponent,   // .. but forget this one and you get a "**'AComponent'** 
                  // is not a known element" error.
  ],
})