【问题标题】:Angular2 RC6: '<component> is not a known element'Angular2 RC6:'<component> 不是已知元素'
【发布时间】:2017-01-13 00:14:37
【问题描述】:

尝试运行我的 Angular 2 RC6 应用程序时,我在浏览器控制台中收到以下错误:

> Error: Template parse errors: 'header-area' is not a known element:
> 1. If 'header-area' is an Angular component, then verify that it is part of this module.
> 2. If 'header-area' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component
> to suppress this message.("

    <div class="page-container">
        [ERROR->]<header-area></header-area>
        <div class="container-fluid">

> "): PlannerComponent@1:2

我不明白为什么找不到该组件。我的 PlannerModule 如下所示:

@NgModule({
  declarations: [
    PlannerComponent,
    HeaderAreaComponent,
    NavbarAreaComponent,
    EreignisbarAreaComponent,
    GraphAreaComponent,
    nvD3
    ],
  imports: [
    RouterModule,
    CommonModule,
    ModalModule
    ],
  bootstrap: [PlannerComponent],
})
export class PlannerModule {}

据我了解 ng2 中模块的概念,模块的各个部分是在“声明”中声明的。为了完整起见,这里是 PlannerComponent:

@Component({
  selector: 'planner',
  providers: [CalculationService],
  templateUrl: './planner.component.html',
  styleUrls: ['./planner.component.styl']
})
export default class PlannerComponent {
}

和 HeaderAreaComponent:

@Component({
  selector: 'header-area',
  templateUrl: './header-area.component.html',
  styleUrls: ['./header-area.component.styl']
})
export default class HeaderAreaComponent {
}

&lt;header-area&gt;-Tag 位于 planner.component.html:

<div class="page-container">
  <header-area></header-area>
  <div class="container-fluid">

    <div class="row">...

我是不是搞错了什么?

更新:完整代码

planner.module.ts:

import HeaderAreaComponent from '../header-area/header-area.component';
import NavbarAreaComponent from '../navbar-area/navbar-area.component';
import GraphAreaComponent from '../graph-area/graph-area.component';
import EreignisbarAreaComponent from '../ereignisbar-area/ereignisbar-area.component';
import PlannerComponent from './planner.component';
import {NgModule} from '@angular/core';
import {nvD3} from 'ng2-nvd3';
import {RouterModule} from '@angular/router';
import {CommonModule} from '@angular/common';
import {ModalModule} from 'ng2-bootstrap/ng2-bootstrap';

@NgModule({
  declarations: [
    PlannerComponent,
    HeaderAreaComponent,
    NavbarAreaComponent,
    EreignisbarAreaComponent,
    GraphAreaComponent,
    nvD3
  ],
  imports: [
    RouterModule,
    CommonModule,
    ModalModule
  ],
  bootstrap: [PlannerComponent],
})
export class PlannerModule {
  // TODO: get rid of the "unused class" warning
}

planner.component.ts

import {Component} from '@angular/core';
import CalculationService from '../_shared/services/calculation.service/calculation.service';
import HeaderAreaComponent from '../header-area/header-area.component';

@Component({
  selector: 'planner',
  providers: [CalculationService],
  templateUrl: './planner.component.html',
  styleUrls: ['./planner.component.styl']
})
export default class PlannerComponent {
}

planner.component.html

<div class="page-container">
  <header-area></header-area>
  <div class="container-fluid">

    <div class="row">
      <div class="col-xs-2 col-sm-1 sidebar">
        <navbar-area></navbar-area>
      </div>
      <div class="col-xs-10 col-sm-11">
        <graph-area></graph-area>
      </div>
    </div><!--/.row-->

    <div class="row">
      <div class="col-xs-10 col-sm-11 offset-sm-1">
        <ereignisbar-area></ereignisbar-area>
      </div>
    </div><!--/.row-->

  </div><!--/.container-->
</div><!--/.page-container-->

【问题讨论】:

  • 为什么你导入HeaderAreaComponent 没有{} 和其他{}。您可以尝试以相同的方式导入它们吗? (也许删除default?)
  • 我删除了默认值并在没有{} 的情况下导入了它,但我得到了相同的结果。

标签: angular


【解决方案1】:

我在将模块 A 导入模块 B 时收到此错误,然后尝试在模块 B 中使用模块 A 中的组件。

解决方案是在exports 数组中声明该组件。

@NgModule({
  declarations: [
    MyComponent
  ],
  exports: [
    MyComponent
  ]
})
export class ModuleA {}
@NgModule({
  imports: [
    ModuleA
  ]
})
export class ModuleB {}

【讨论】:

  • 当然,Angular 的组件文档甚至都没有提到这一点。
  • 我已经为这个挠头一天了!非常感谢!
【解决方案2】:

我在 Sanket's answer 和 cmets 的帮助下修复了它。

您不知道并且在错误消息中不明显的是:我将 PlannerComponent 作为 @NgModule.declaration 导入到我的应用模块 (= RootModule )。

通过将 PlannerModule 导入为 @NgModule.imports 修复了错误。

之前:

@NgModule({
  declarations: [
    AppComponent,
    PlannerComponent,
    ProfilAreaComponent,
    HeaderAreaComponent,
    NavbarAreaComponent,
    GraphAreaComponent,
    EreignisbarAreaComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routeConfig),
    PlannerModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule {

之后:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routeConfig),
    PlannerModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

感谢您的帮助:)

【讨论】:

  • 我编辑了您的答案以更改格式以使差异更清晰。现在我已经这样做了,我发现不同之处在于您只是从declarations 中删除了一些项目。这可能是对的吗?
  • 杰普,没错。 AppModule 和 PlannerModule 是两个独立的东西,我在两者中声明了一些组件。它通过在一个模块中声明一个组件并在另一个模块中导入该模块来工作。
  • 感谢您发布您的解决方案,但在“之前”部分中,您还显示为导入的 PlannerModule
【解决方案3】:

如果您使用过 Webclipse 自动生成的组件定义,您可能会发现选择器名称前附加了“app-”。显然,这是在声明主应用程序组件的子组件时的新约定。如果您使用 'new' - 'component' 在 Angular IDE 中创建选择器,请检查您的选择器是如何在组件中定义的。所以不要放

<header-area></header-area>

你可能需要

<app-header-area></app-header-area>

【讨论】:

  • ng cli 生成的组件也是如此。
  • 如果我生成一个带有--selector 选项的组件,那么我不需要在app- 前面加上组件标签。例如:ng generate component menu-list --selector 'menu-list'
  • 不敢相信这是我的问题.. :/ 谢谢!点赞!!
【解决方案4】:

我为 &lt;flash-messages&gt;&lt;/flash-messages&gt; 获取了同样的问题,角度为 5。

您只需在 app.module.ts 文件中添加以下行

import { ---, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { FlashMessageModule } from "angular-flash-message";


@NgModule({
  ---------------
  imports: [
    FlashMessageModule,
    ------------------         
  ], 
  -----------------
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
  ------------
})

注意:我正在使用这个消息flash-messages

【讨论】:

  • 自 2 小时以来我遇到的问题的唯一解决方案
【解决方案5】:

在您的 planner 组件中,您必须像这样缺少 import HeaderAreaComponent -

import { HeaderAreaComponent } from '../header-area.component'; 
//change path according your project

另外,请确保 - 所有组件和管道都必须通过 NgModule 声明

看看这是否有帮助。

【讨论】:

  • 很遗憾没有 - 错误保持不变,导入被 lint 标记为未使用。
  • 能否请您发布您的 NgModule 和规划器组件的完整代码?
  • 除了上面的 Gunter 建议外,还可以尝试像这样在您的规划器组件中导入 BrowserModule-import { BrowserModule } from '@angular/platform-browser';
  • 我在规划器组件和模块中将其导入并声明为导入 - 仍然没有成功。
  • 现在尝试像这样在 NgModule 的提供者中添加 CalculationService-providers: [CalculationService],
【解决方案6】:

我在 Angular 7 上遇到了这个问题,问题是在创建模块后,我没有执行 ng build。所以我表演了-

  • ng build
  • ng serve

它成功了。

【讨论】:

  • 再次运行 ng serve 为我做了这件事,虽然很蹩脚
【解决方案7】:

当组件在主应用程序页面中超出&lt;router-outlet&gt; 时,单元测试中出现错误。 所以应该在测试文件中定义组件,如下所示。

<app-header></app-header>
<router-outlet></router-outlet>

然后需要在spec.ts文件中添加如下。

import { HeaderComponent } from './header/header.component';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        App`enter code here`Component,
        HeaderComponent <------------------------
      ],
    }).compileComponents();
  }));
});

【讨论】:

    【解决方案8】:

    出现相同错误消息的另一个可能原因是标签名称和选择器名称不匹配。对于这种情况:

    &lt;header-area&gt;&lt;/header-area&gt; 标签名称必须与组件声明中的'header-area' 完全匹配:

    @Component({
      selector: 'header-area',
    

    【讨论】:

      【解决方案9】:

      我遇到了同样的问题,我通过在声明我的组件的模块 (ModuleLower) 的导出数组中添加组件 (MyComponentToUse) 来解决此问题。 然后我在 ModuleHigher 中导入 ModuleLower,所以我现在可以在 ModuleLower 和 ModuleHigher 中重用我的组件(MyComponentToUse)

                  @NgModule({
                    declarations: [
                      MyComponentToUse
                    ],
                    exports: [
                      MyComponentToUse
                    ]
                  })
                  export class ModuleLower {}
      
      
                  @NgModule({
                    imports: [
                      ModuleLower
                    ]
                  })
                  export class ModuleHigher {} 
      

      【讨论】:

      • 没错,只需要导出组件。
      • 你救了我。非常感谢!
      【解决方案10】:

      由于某种原因,我在 Angular RC.6 上遇到了同样的问题,它不允许使用指令作为父组件的组件装饰器将组件传递给其他组件

      但是如果您通过 app 模块导入子组件并将其添加到声明数组中,错误就会消失。没有太多解释为什么这是 angular rc.6 的问题

      【讨论】:

        【解决方案11】:

        当我遇到这个问题时,是因为我在装饰器中使用了'templateUrl'而不是'template',因为我使用webpack并且需要使用require在里面。请注意装饰器名称,在我的例子中,我使用 sn-p 生成了样板代码,装饰器被创建为:

        @Component({
          selector: '',
          templateUrl: 'PATH_TO_TEMPLATE'
        })
        

        但对于 webpack,装饰器应该只是 'template' NOT 'templateUrl',如下所示:

        @Component({
          selector: '',
          template: require('PATH_TO_TEMPLATE')
        })
        

        改变这个解决了我的问题。

        想了解更多关于这两种方法的信息吗?阅读this medium post about template vs templateUrl

        【讨论】:

          【解决方案12】:

          当我导出的文件名和类不匹配时出现此错误:

          文件名:list.component.ts

          类导出:ListStudentsComponent

          ListStudentsComponent 更改为 ListComponent 解决了我的问题。

          【讨论】:

            【解决方案13】:

            我遇到了这个确切的问题。 失败:模板解析错误: 'app-login' 不是已知元素...ng test。我尝试了上述所有回复:没有任何效果。

            NG 测试解决方案:

            Angular 2 Karma Test 'component-name' is not a known element

            beforEach(.. declarations[]) 到 app.component.spec.ts

            示例 app.component.spec.ts

            ...
            import { LoginComponent } from './login/login.component';
            ...
            describe('AppComponent', () => {
              beforeEach(async(() => {
                TestBed.configureTestingModule({
                  imports: [
                    ...
                  ],
                  declarations: [
                    AppComponent,
                    LoginComponent
                  ],
                }).compileComponents();
              ...
            

            【讨论】:

              【解决方案14】:

              在我的案例中,一个新手错误生成了相同的错误消息。

              app-root 标签不在 index.html 中

              【讨论】:

                【解决方案15】:

                templateUrl 的路径不正确

                我正在使用

                shopping-list-edit.component.html

                应该是这样的

                ./shopping-list-edit.component.html

                愚蠢的错误,但在开始时发生。希望能帮助有困难的人。

                【讨论】:

                  【解决方案16】:

                  当我打算通过声明测试组件来优化测试模块时,我遇到了与 Angular 7 相同的问题。刚刚添加schemas: [ CUSTOM_ELEMENTS_SCHEMA ]如下,错误已解决。

                  TestBed.configureTestingModule({
                    imports: [ReactiveFormsModule, FormsModule],
                    declarations: [AddNewRestaurantComponent],
                    schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
                  });
                  

                  【讨论】:

                    【解决方案17】:

                    对于未来的问题。 如果您认为您遵循了所有好的答案,但问题就在那里。

                    尝试关闭再打开服务器。

                    我遇到了同样的问题,按照所有步骤,无法解决。关闭,打开,它是固定的。

                    【讨论】:

                    • 首先我以为我只需要重启npm start(在水下ng serve)。这有时有助于解决问题。现在我不得不完全重新启动 Visual Studio Code。
                    【解决方案18】:

                    OnInit 是在我的课堂上自动实现的,同时使用 angular CLI 上的 ng new ... 关键字生成新组件。所以在我去掉了实现,去掉了生成的空方法之后,问题就解决了。

                    【讨论】:

                      【解决方案19】:

                      好的,我来详细介绍一下代码,如何使用其他模块的组件。

                      例如我有M2模块,M2模块有comp23组件和comp2组件,现在我想在app.module中使用comp23和comp2,方法如下:

                      这是app.module.ts,看我的评论,

                       // import this module's ALL component, but not other module's component, only this module
                        import { AppComponent } from './app.component';
                        import { Comp1Component } from './comp1/comp1.component';
                      
                        // import all other module,
                       import { SwModule } from './sw/sw.module';
                       import { Sw1Module } from './sw1/sw1.module';
                       import { M2Module } from './m2/m2.module';
                      
                         import { CustomerDashboardModule } from './customer-dashboard/customer-dashboard.module';
                      
                      
                       @NgModule({
                      
                          // declare only this module's all component, not other module component.  
                      
                      declarations: [
                      AppComponent,
                      Comp1Component,
                      
                      
                       ],
                      
                       // imports all other module only.
                      imports: [
                      BrowserModule,
                      SwModule,
                      Sw1Module,
                      M2Module,
                      CustomerDashboardModule // add the feature module here
                      ],
                       providers: [],
                       bootstrap: [AppComponent]
                      })
                      export class AppModule { }
                      

                      这是 m2 模块:

                         import { NgModule } from '@angular/core';
                         import { CommonModule } from '@angular/common';
                      
                         // must import this module's all component file
                         import { Comp2Component } from './comp2/comp2.component';
                         import { Comp23Component } from './comp23/comp23.component';
                      
                         @NgModule({
                      
                         // import all other module here.
                           imports: [
                             CommonModule
                           ],
                      
                          // declare only this module's child component. 
                           declarations: [Comp2Component, Comp23Component],
                      
                         // for other module to use these component, must exports
                           exports: [Comp2Component, Comp23Component]
                         })
                         export class M2Module { }
                      

                      我在代码中的推荐解释了你需要在这里做什么。

                      现在在 app.component.html 中,你可以使用

                        <app-comp23></app-comp23>
                      

                      关注角度文档sample import modul

                      【讨论】:

                        【解决方案20】:

                        该线程的答案较晚,但我相信有更多的人可以使用从另一个角度解释的此信息。

                        在 Ionic 中,自定义角度组件被组织在一个名为 ComponentsModule 的单独模块下。当使用ionic generate component 生成第一个组件时,离子连同该组件一起生成ComponentsModule。任何后续组件都会添加到同一个模块中,这是正确的。

                        这是一个示例ComponentsModule

                        import { NgModule } from '@angular/core';
                        import { CustomAngularComponent } from './custom/custom-angular-component';
                        import { IonicModule } from 'ionic-angular';
                        @NgModule({
                            declarations: [CustomAngularComponent],
                            imports: [IonicModule],
                            exports: [CustomAngularComponent],
                            entryComponents:[
                        
                              ]
                        })
                        export class ComponentsModule {}
                        

                        要在应用程序中使用ComponentsModule,就像任何其他角度模块一样,需要将ComponentsModules 导入AppModule。 ionic generate 组件(v 4.12)没有添加这一步,所以必须手动添加。

                        AppModule 摘录:

                        @NgModule({
                          declarations: [
                            //declaration
                          ],
                          imports: [
                            //other modules 
                            ComponentsModule,
                          ],
                          bootstrap: [IonicApp],
                          entryComponents: [
                            //ionic pages
                          ],
                          providers: [
                            StatusBar,
                            SplashScreen,
                            {provide: ErrorHandler, useClass: IonicErrorHandler},
                            //other providers
                          ]
                        })
                        export class AppModule {}
                        

                        【讨论】:

                          【解决方案21】:

                          人为错误 - 不要被错误消息误导。

                          为什么我被误导了:我想使用的组件 (ComponentA) 在它的模块 (ModuleA) 中被正确声明。它也被正确地导出到那里。我正在使用的组件 (ComponentB) 的模块 (ModuleB) 正确指定了 ModuleA 的导入。 但是,由于错误消息是 不是已知元素',我的全部重点是认为这是 ModuleA/ComponentA 的问题,因为这就是错误消息所包含的内容;我没有考虑查看我试图从中使用它的组件。我关注了每一个关于此威胁的帖子,但最终错过了一个重要步骤:

                          为我解决了什么问题: frot.io's answer 提示我检查我的 app.module.ts 导入列表,我正在使用的组件 (ComponentB) 不包括在内!

                          【讨论】:

                          • 是的,只是掉进了那个陷阱。谢谢。
                          猜你喜欢
                          • 2017-05-07
                          • 2021-09-02
                          • 2017-06-13
                          • 2017-01-20
                          • 2017-11-14
                          • 2017-08-20
                          • 2017-03-10
                          • 2017-03-11
                          • 1970-01-01
                          相关资源
                          最近更新 更多