Angular2 RC6: '<component>は既知の要素ではありません'


128

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 {
}

<header-area>-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-->

1
HeaderAreaComponentなし{}でインポートし、その他でインポートするのはなぜですか{}。同じ方法でインポートしてみませんか?(おそらく削除しdefaultますか?)
ギュンターZöchbauer

デフォルトを削除してなし{}でインポートしましたが、同じ結果が得られます。
frot.io 2016

回答:


252

モジュールAをモジュールBにインポートし、モジュールAのコンポーネントをモジュールBで使用しようとすると、このエラーが発生しました。

解決策は、そのコンポーネントを exports配列で。

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

52
そして当然のことながら、コンポーネントに関するAngularのドキュメントではこれについてさえ言及されていません。
John

私はこれに頭を悩ませていました。どうもありがとうございます!
EGC

34

Sanketの答え参考にして修正しましたとコメント。

あなたが知ることができず、エラーメッセージで明らかでなかったのは、私が自分のApp Module(= RootModule)に@ NgModule.declarationとしてPlannerComponentをインポートしたことです

このエラーは、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 {
}

ご協力いただきありがとうございます :)


1
あなたの答えを編集して、違いをより明確にするために書式を変更しました。これを実行したので、違いは、単にから多数のアイテムを削除したことですdeclarations。これは正しいでしょうか?
Jason Swett、2016

1
ジェップ、そうだね。AppModuleとPlannerModuleは2つの別個のものであり、両方でいくつかのコンポーネントを宣言しました。1つのモジュールでのみコンポーネントを宣言し、このモジュールを他のモジュールにインポートすることで機能します。
frot.io 16

ソリューションを投稿していただきありがとうございます。ただし、「前」セクションでは、PlannerModule
Juan Monsalve

23

Webclipseで自動生成されたコンポーネント定義を使用した場合、セレクター名の前に「app-」が付加されていることがあります。明らかにこれは、メインアプリコンポーネントのサブコンポーネントを宣言するときの新しい規則です。Angular IDEでセレクターを作成するために 'new'-'component'を使用した場合は、コンポーネントでセレクターがどのように定義されているかを確認してください。だから置く代わりに

<header-area></header-area>

あなたが必要があるかもしれません

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

1
同じことがngcli によって生成されたコンポーネントにも当てはまります。
探検家

--selectorオプション付きのコンポーネントを生成する場合app-、コンポーネントタグをプレフィックスとして付ける必要はありません。例:ng generate component menu-list --selector 'menu-list'
エクスプローラー

これが私の問題だとは信じられません。賛成!
サックス奏者

8

私は同じ問題をフェッチします <flash-messages></flash-messages>Angular 5でもます。

app.module.tsファイルに以下の行を追加するだけです

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


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

注意:私はこれをメッセージのフラッシュメッセージに使用しています


2時間以来直面していた私の問題に対する唯一の解決策
ベロニカ、

7

あなたのプランナーコンポーネントでは、このようなインポートHeaderAreaComponentが欠落している必要があります-

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

また、確認してください- すべてのコンポーネントとパイプはNgModuleを介して宣言する必要があります

これが役立つかどうかを確認します。


残念ながらできません-エラーは同じままで、インポートはlintによって未使用としてマークされます。
frot.io 2016

NgModuleとplannerコンポーネントの完全なコードを投稿できますか?
Sanket

1
上記ギュンターの提案に加えて、またthis-のようなあなたのプランナーのCompoNetをにインポートBrowserModuleにしてみてくださいimport { BrowserModule } from '@angular/platform-browser';
Sanket

私はそれをインポートとして宣言して、plannerコンポーネントとモジュールにインポートしました-それでも成功しません。
frot.io 2016

1
次に、このようにNgModuleのプロバイダーにCalculationServiceを追加してみますproviders: [CalculationService],
Sanket

6

Angular 7でこの問題に直面していましたが、問題はモジュールの作成後に発生し、実行しませんでしたng build。だから私は-

  • ng build
  • ng serve

そしてそれは働いた。


ちょうどNGは再びサーブ実行すると、私のためにかかわらず、かなりラメそれをやった
Elger Mensonides

4

コンポーネントが<router-outlet>メインアプリページにない場合、ユニットテストでエラーが発生します。以下のようにテストファイルでコンポーネントを定義する必要があります。

<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();
  }));
});

3

同じエラーメッセージが表示される別の原因として、タグ名とセレクター名の不一致が考えられます。この場合:

<header-area></header-area>タグ名'header-area'はコンポーネント宣言と完全に一致する必要があります:

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

2

何らかの理由で角度付きRC.6で同じ問題がありましたが、ディレクティブを親コンポーネントのコンポーネントデコレータとして使用してコンポーネントを他のコンポーネントに渡すことができません

ただし、アプリモジュールを介して子コンポーネントをインポートして宣言配列に追加すると、エラーは発生しなくなります。これがangular rc.6の問題である理由についてはあまり説明がありません。


2

この問題が発生したのは、デコレータで「テンプレート」ではなく「テンプレートUrl」を使用したためです。これwebpackを使用し、それにrequireを使用する必要があるためです。デコレーター名に注意してください。私の場合、スニペットを使用してボイラープレートコードを生成しました。デコレーターは次のように作成されました。

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

ただし、webpackの場合、デコレータは次のように ' template ' NOT ' templateUrl 'にする必要があります。

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

これを変更すると、問題が解決しました。

2つの方法についてもっと知りたいですか?vs に関するこの中程度の投稿を読んでくださいtemplatetemplateUrl


2

ファイル名とエクスポートされたクラスの不一致があると、このエラーが発生しました。

ファイル名:list.component.ts

エクスポートされたクラス:ListStudentsComponent

以下からの変更ListStudentsComponentListComponentは私の問題を修正しました。


2

私はこの正確な問題に遭遇しました。失敗:テンプレート解析エラー: 'app-login'は既知の要素ではありません...ng test。上記の返信をすべて試しましたが、何もうまくいきませんでした。

NGテストソリューション:

Angular 2 Karma Test 'component-name'は既知の要素ではありません

<=問題のあるコンポーネントの宣言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();
  ...

2

同じ問題があり、コンポーネントが宣言されたモジュール(ModuleLower)のexports配列にコンポーネント(MyComponentToUse)を追加して修正しました。次にModuleLowerをModuleHigherにインポートして、ModuleLowerとModuleHigherでコンポーネント(MyComponentToUse)を再利用できるようにします

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


            @NgModule({
              imports: [
                ModuleLower
              ]
            })
            export class ModuleHigher {} 

まさに、コンポーネントをエクスポートする必要があるだけです。
Rohit Parte

1

テストコンポーネントを宣言してテストモジュールを改良しようとすると、Angular 7でも同じ問題が発生しました。schemas: [ CUSTOM_ELEMENTS_SCHEMA ]以下のように追加するだけでエラーが解消されました。

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

1

将来の問題について。あなたがすべての良い答えに従ったとまだ思っているなら、問題はそこにあります。

サーバーの電源を入れ直してみてください。

私は同じ問題を抱えており、すべての手順を踏んでも解決できませんでした。オフにして、オンにすると修正されました。


最初は、npm start(水中でng serve)再起動するだけでよいと思いました。それは時々問題を解決するのに役立ちます。ここでVisual Studio Codeを完全に再起動する必要がありました。
Mike de Klerk

0

私の場合、初心者の間違いが同じエラーメッセージを生成していました。

app-rootタグは、index.htmlを中に存在していませんでした


0

OnInitng new ...Angular CLIのキーフレーズを使用して新しいコンポーネントを生成しているときに、クラスに自動的に実装されました。したがって、実装を削除し、生成された空のメソッドを削除すると、問題は解決します。


0

私にとって、templateUrlのパスが正しくありませんでした

使っていた

shopping-list-edit.component.html

それがあるべきだったのに対し

./shopping-list-edit.component.html

愚かな間違いですが、開始時に発生します。それが苦痛の誰かを助けることを願っています。


0

スレッドに対する回答は遅くなりますが、この情報を別の視点で説明したものを使用できる人はもっと多いと思います。

Ionicでは、カスタムアングルコンポーネントは、という別のモジュールの下に編成されますComponentsModule。を使用して最初のコンポーネントが生成されるionic generate componentと、コンポーネントとともに、ionicがを生成し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 {}

-1

では、コードの詳細と、他のモジュールのコンポーネントの使い方を説明しましょう。

たとえば、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>

角度付きドキュメントサンプルインポートモジュールに従います

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.