首页 > 解决方案 > 不断获得未捕获(承诺):错误:模板解析错误:“组件”不是已知元素:

问题描述

下面是一些代码片段。

零件:

import { Component } from '@angular/core';

@Component({
 selector: 'app-generalstatistics',
 templateUrl: './generalstatistics.component.html',
 styleUrls: ['./generalstatistics.component.css']
})
export class Generalstatistics  {
 public data: Array<Object>;
 constructor() { }
}

app.module.ts:

import { Generalstatistics } from './views/generalstatistics/generalstatistics.component';

   declarations: [
   ....
   Generalstatistics
],

DashboardModule/DashboardComponent.html 中的实现:

<div class="chart-wrapper mt-3 mx-3" style="height:70px;">
      <app-generalstatistics></app-generalstatistics>
    </div>

错误:

core.js:4002 ERROR Error: Uncaught (in promise): Error: Template parse errors:
'app-generalstatistics' is not a known element:
1. If 'app-generalstatistics' is an Angular component, then verify that it is part of this module.
2. If 'app-generalstatistics' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the 
'@NgModule.schemas' of this component to suppress this message. ("
    </div>
    <div class="chart-wrapper mt-3 mx-3" style="height:70px;">
      [ERROR ->]<app-generalstatistics></app-generalstatistics>
    </div>
  </div>
 "): ng:///DashboardModule/DashboardComponent.html

我到底做错了什么?

感谢帮助。

标签: angularangular-components

解决方案


我假设您也应该将app-generalstatistics组件添加到declarations: []您的组件中DashboardModule(实际上就是您使用它的地方)

Afaik NgModule 是模板的编译上下文。所以我们必须在使用它的每个模块中声明一个组件。

为什么?在我看来:否则编译可能需要一段时间,因为在这种情况下,Angular 将不得不去搜索组件定义,并且可能存在任何依赖项,包括第 3 方。


推荐阅读