Angular 2 'component' 不是已知元素

Angular 2 'component' is not a known element

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

"Uncaught (in promise): Error: Template parse errors:

'contacts-box' is not a known element:

  1. If 'contacts-box' is an Angular component, then verify that it is part of this module.
  2. If 'contacts-box' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

我的项目结构很简单:

我将我的页面保存在 pages 目录中,每个页面保存在不同的模块(例如客户模块)中,每个模块都有多个组件(例如客户列表组件、客户添加组件等) .我想在这些组件中使用我的 ContactBoxComponent(例如在 customers-add-component 中)。

如您所见,我在 widgets 目录中创建了 contacts-box 组件,因此它基本上位于 AppModule 中。我将 ContactBoxComponent 导入添加到 app.module.ts 并将其放入 AppModule 的声明列表中。它没有用,所以我用谷歌搜索了我的问题并将 ContactBoxComponent 添加到导出列表中。没有帮助。我还尝试将 ContactBoxComponent 放在 CustomersAddComponent 中,然后放在另一个(来自不同模块)中,但我收到一条错误消息,说有多个声明。

我错过了什么?

这些是我遇到此类错误时执行的 5 个步骤。

  • 你确定这个名字是正确的吗? (还要检查组件中定义的选择器)
  • 在模块中声明组件?
  • 如果在另一个模块中,导出组件?
  • 如果在另一个模块中,导入那个模块?
  • 重启客户端?

如果在单元测试中出现错误,请确保您在TestBed.configureTestingModule

中声明了组件或导入了模块

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.

你不能声明一个组件两次。您应该在一个新的单独模块中声明和导出您的组件。接下来,您应该在要使用您的组件的每个模块中导入这个新模块。

很难说什么时候应该创建新模块,什么时候不应该。我通常为我重用的每个组件创建一个新模块。当我有一些我几乎无处不在的组件时,我将它们放在一个模块中。当我有一个我不重复使用的组件时,我不会创建一个单独的模块,直到我在其他地方需要它。

虽然将所有组件放在一个模块中可能很诱人,但这对性能不利。在开发过程中,每次进行更改时都必须重新编译模块。模块越大(组件越多)花费的时间就越多。对大模块做一个小改动比对小模块做一个小改动要花更多的时间。

我刚刚遇到了完全相同的问题。在尝试此处发布的一些解决方案之前,您可能需要检查组件 really 是否不起作用。对我来说,错误显示在我的 IDE (WebStorm) 中,但事实证明,当我在浏览器中 运行 时,代码运行完美。

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

我有同样的问题宽度php风暴版本2017.3。这为我解决了: intellij support forum

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

我遇到了类似的问题。事实证明,ng generate component(使用 CLI 版本 7.1.4)将子组件的声明添加到 AppModule,但没有添加到模拟它的 TestBed 模块。

"Tour of Heroes" 示例应用程序包含 HeroesComponent 和选择器 app-heroes。应用程序 运行 运行良好,但 ng test 产生了此错误消息:'app-heroes' is not a known element。将 HeroesComponent 手动添加到 configureTestingModule 中的声明(在 app.component.spec.ts 中)消除了此错误。

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        HeroesComponent
      ],
    }).compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  });
}

我遇到了同样的问题,它的发生是因为不同的功能模块错误地包含了这个组件。当从其他功能中删除它时,它起作用了!

我的问题是模块中缺少组件声明,但即使在添加声明后错误仍然存​​在。我已停止服务器并在 VS Code 中重建整个项目以使错误消失。

在我的例子中,我的应用程序有多层模块,所以我尝试导入的模块必须添加到实际使用它的模块父 pages.module.ts,而不是 app.module.ts .

这个复杂的框架让我抓狂。鉴于您在 SAME 模块的另一个组件部分的模板中定义了自定义组件,那么您不需要在模块中使用导出(例如 app.module.ts)。您只需要在上述模块的@NgModule 指令中指定声明:

// app.module.ts

import { JsonInputComponent } from './json-input/json-input.component';

@NgModule({
  declarations: [
    AppComponent,
    JsonInputComponent
  ],
  ...

您不需要将 JsonInputComponent(在此示例中)导入 AppComponent(在此示例中)以在 AppComponent 模板中使用 JsonInputComponent 自定义组件.您只需要在自定义组件前面加上两个组件都已定义的模块名称(例如 app):

<form [formGroup]="reactiveForm">
  <app-json-input formControlName="result"></app-json-input>
</form>

注意 app-json-input 不是 json-input!

此处演示:https://github.com/lovefamilychildrenhappiness/AngularCustomComponentValidation

我开始 Angular,在我的例子中,问题是我在添加 'import' 语句后没有保存文件。

路由模块(未将此视为答案)

首先检查: 如果您已经在其模块中声明并导出组件,则导入模块你想使用它并在 HTML.

中正确命名组件

否则,您可能会错过路由模块中的一个模块:
当您的路由模块具有从另一个模块路由到组件的路由时,在该路由模块中导入该模块很重要。否则 Angular CLI 将显示错误:component is not a known element.

例如

1) 具有以下项目结构:

├───core
│   └───sidebar
│           sidebar.component.ts
│           sidebar.module.ts
│
└───todos
    │   todos-routing.module.ts
    │   todos.module.ts
    │
    └───pages
            edit-todo.component.ts
            edit-todo.module.ts

2) 在 todos-routing.module.ts 中,您有一条通往 edit.todo.component.ts 的路径(无需导入其模块):

  {
    path: 'edit-todo/:todoId',
    component: EditTodoComponent,
  },

这条路线会很好!但是,当在 edit-todo.module.ts 中导入 sidebar.module.ts 时,您将收到错误消息:app-sidebar is not a known element.

修复: 由于您在步骤 2 中添加了到 edit-todo.component.ts 的路由,因此您必须添加 edit-todo.module.ts 作为导入,之后导入的侧边栏组件将起作用!

我遇到了同样的问题。就我而言,我忘记在 app.module.ts

例如,如果您在 ToDayComponent 模板中使用 <app-datapicker> 选择器,则应在 [= 中声明 ToDayComponentDatepickerComponent 22=]

假设你有一个组件:

产品-list.component.ts:

import { Component } from '@angular/core';
    
    @Component({
        selector: 'pm-products',  
        templateUrl: './product-list.component.html'
    })
    
    
    export class ProductListComponent {
      pageTitle: string = 'product list';
    }

你得到这个错误:

ERROR in src/app/app.component.ts:6:3 - error NG8001: 'pm-products' is not a known element:

  1. If 'pm-products' is an Angular component, then verify that it is part of this module.

app.component.ts:

import { Component } from "@angular/core";
@Component({
  selector: 'pm-root', // 'pm-root'
  template: `
  <div><h1>{{pageTitle}}</h1>
  <pm-products></pm-products> // not a known element ?
  </div>
  `
})
export class AppComponent {
  pageTitle: string = 'Acme Product Management';
}

确保导入组件:

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

// --> add this import (you can click on the light bulb in the squiggly line in VS Code)
import { ProductListComponent } from './products/product-list.component'; 

@NgModule({
  declarations: [
    AppComponent,
    ProductListComponent // --> Add this line here

  ],
  imports: [
    BrowserModule
  ],
  bootstrap: [AppComponent],


})
export class AppModule { }

这个问题可能看起来古老而奇怪,但是当我尝试加载模块(延迟加载)并遇到相同的错误时,我意识到我缺少组件的 exports 子句 作为更大模块的一部分发货。

This Angular.io Link explains why: Components/Services 在模块内,默认情况下保持私有(或受保护)。要制作它们 public,您必须导出它们。

扩展 with ,这是我的案例中技术上缺失的内容 (Angular 8):

@NgModule({
  declarations: [
    SomeOtherComponent,
    ProductListComponent
  ],
  imports: [
    DependantModule
  ],
  exports: [ProductListComponent] 
  //<- This line makes ProductListComponent available outside the module, 
  //while keeping SomeOtherComponent private to the module
})
export class SomeLargeModule { }

很多 answers/comments 提到在其他模块中定义的组件,或者你必须 import/declare 组件(你想在另一个模块中使用its/their 中的组件)包含模块。

但是在简单的情况下,如果您想使用组件 B 中的组件 A,当两者都定义在同一个模块中时,您必须声明 both 包含模块中的组件 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.
  ],
})

我在使用 Angular CLI 时遇到了同样的问题:10.1.5 代码工作正常,但错误显示在 VScode v1.50

通过终止终端(ng serve)和重启VScode.

解决

我知道这是一个长期解决的问题,但就我而言,我有不同的解决方案。 这实际上是我犯的一个错误,也许你也犯了,但没有完全注意到。我的错误是我不小心在声明部分放置了一个模块,例如 MatChipsModule、MatAutoCompleteModule;仅由组件组成的部分,例如 MainComponent、AboutComponent。这让我的所有其他导入都无法识别。

我花了半天时间来解决这个问题。问题出在进口上。我的 HomeModule 有 homeComponent,它包含在 html 中。 ProductComponent 是 ProductModule 的一部分。我在 HomeModule 的导入中添加了 ProductModule,但忘记在 AppModule 的导入中添加 HomeModule。添加后问题消失

在执行 Angular 的 Getting Started Tutorial 时,我在使用 Angular 生成器通过工具 [=] 生成名为 product-alerts 的新组件后也收到此错误20=].

'app-product-alerts' is not a known element:

发现:其他人在 2021 年 8 月上旬也遇到过它。目前,它似乎是 StackBlitz IDE 中的一个错误。 https://github.com/angular/angular/issues/43020

有时甚至只是重新启动 IDE 就可以了!! 遇到同样的问题,通过重启 VS Code 解决

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

我的步骤:

  1. 生成新的页面组件
  2. 将现有组件导入新页面的 module.ts 文件
  3. 在新页面的HTML文件中使用<myapp-header></myapp-header>组件选择器

收到错误并卡在此处。我的最后一步是:

  1. 将新页面模块导入 pages.module.ts 文件。

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

对于我的应用程序模式,一旦我在 app.module.ts 文件中声明了我的 LandingPageComponent,就可以将子模块导入其中。

我刚刚开始了一个新项目,并且认为其中一些模式是理所当然的。

我遇到了类似的问题,但 none 提到的解决方案有效。最后我意识到我有一个路由问题:

我想如果我像这样在 app-routing.module 中指定我的组件:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MainComponent } from './pages/main/main.component';

const routes: Routes = [
  {
    path: '', 
    component: MainComponent
  },
]

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

我不必在我的 AppModule 中导入 MainModule,这是错误的,因为这里只导入了组件。在 MainModule 中声明的任何其他组件将不可见,这会导致您描述的错误消息。

解决方案 1:
导入声明模块
解决方案 2:
像这样延迟加载组件:

const routes: Routes = [
{
    path: '', loadChildren: () => import('path_to_your_module').then(m => m.MainModule)},
}

这是有效的,因为整个模块都在这里导入。

我知道您在您的示例中没有使用路由,只是将此发布给可能使用路由并偶然发现这个问题的任何其他人。