ChatGPT解决这个技术问题 Extra ChatGPT

Angular2 RC6: '<component> is not a known element'

I am getting the following error in the browser console when trying to run my Angular 2 RC6 app:

> 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

I don't get why the component isn't found. My PlannerModule looks like this:

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

and as far as I understood the concept of Modules in ng2, the parts of the modules are declared in 'declarations'. For completeness, here is the PlannerComponent:

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

and the HeaderAreaComponent:

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

The <header-area>-Tag is located in planner.component.html:

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

    <div class="row">...

Did I get something wrong?

Update: Complete code

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-->
Why do you import HeaderAreaComponent without {} and the others with {}. Can you try to import them the same way? (perhaps removing the default?)
I removed the default and imported it without {}, but I get the same result.

S
Stephen Paul

I received this error when I imported Module A into Module B, and then tried to use a component from Module A in Module B.

The solution is to declare that component in the exports array.

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

And naturally, Angular's documentation on components doesn't even mention this.
I'd been scratching my head over this one for a day! Thankyou so much!
C
Community

I fixed it with help of Sanket's answer and the comments.

What you couldn't know and was not apparent in the Error Message is: I imported the PlannerComponent as a @NgModule.declaration in my App Module (= RootModule).

The error was fixed by importing the PlannerModule as @NgModule.imports.

Before:

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

After:

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

Thanks for your help :)


I edited your answer to change the formatting to make the difference clearer. Now that I've done this, I see that it seems that the difference is that you simply removed a number of items from declarations. Could this be right?
Jepp, that's right. AppModule and PlannerModule are two seperate things, and I declared some components in both. It works by declaring a component in only one module and importing this module within the other.
thanks for posting your solution, but in the "before" section you also show as imported the PlannerModule
F
FayeB

If you have used the Webclipse automatically generated component definition you may find that the selector name has 'app-' prepended to it. Apparently this is a new convention when declaring sub-components of a main app component. Check how your selector has been defined in your component if you have used 'new' - 'component' to create it in Angular IDE. So instead of putting

<header-area></header-area>

you may need

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

Same is true with components generated by ng cli too.
If I generate a component with --selector option, then I do not need to prefix app- with the component tag. Ex: ng generate component menu-list --selector 'menu-list'
Cannot believe this was my issue.. :/ Thank you! Upvoted!!
r
reza.cse08

I fetch same problem for <flash-messages></flash-messages> with angular 5.

You just need add below lines in app.module.ts file

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


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

NB: I am using this one for message flash-messages


Only solution for my problem I was facing since 2 hours
M
Marc

In your planner component, you must be missing import HeaderAreaComponent like this-

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

Also, make sure - All the components and pipes must be declared via an NgModule.

See if this helps.


Unfortunately not - the error stays the same and the import is marked as unused by lint.
can you please post complete code of your NgModule and planner component?
In addition to Gunter suggestion above, also try to import BrowserModule in your planner componet like this- import { BrowserModule } from '@angular/platform-browser';
I imported it in the planner component and in module with declaring it as import - still no success.
now try adding CalculationService in providers of NgModule like this- providers: [CalculationService],
S
Shailesh Pratapwar

I was facing this issue on Angular 7 and the problem was after creating the module, I did not perform ng build. So I performed -

ng build

ng serve

and it worked.


just running ng serve again did it for me, quite lame though
F
Farzad.Kamali

The error coming in unit test, when component is out of <router-outlet> in main app page. so should define the component in test file like below.

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

and then needs to add in spec.ts file as below.

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

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

A
Alexei - check Codidact

Another possible cause of having the same error message is a mismatch between tag name and selector name. For this case:

<header-area></header-area> tag name must exactly match 'header-area' from the component declaration:

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

I
Ilyes CHERIF

I had the same problem and i fixed by adding the component (MyComponentToUse) in exports array in the module where my component was declared (ModuleLower). Then i import ModuleLower in ModuleHigher, so i can reuse now my component ( MyComponentToUse) in the ModuleLower and the ModuleHigher

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


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

Exactly, Just need to export component.
You save me. Thanks a lot!
E
Emmanuel Mariki

I had the same issue with angular RC.6 for some reason it doesn't allow passing component to other component using directives as component decorator to the parent component

But it if you import the child component via app module and add it in the declaration array the error goes away. There are no much explanation to why this is an issue with angular rc.6


L
Leo Bottaro

When I had this problem, it was because I used 'templateUrl' instead of just 'template' in the decorator, since I use webpack and need to use require in it. Just be careful with the decorator name, in my case I generated the boilerplate code using a snippet, the decorator was created as:

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

but for webpack the decorator should be just 'template' NOT 'templateUrl', like so:

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

changing this solved the problem for me.

wanna know more about the two methods? read this medium post about template vs templateUrl


G
GonnaGetGet

I got this error when I had a filename and class exported mismatch:

filename: list.component.ts

class exported: ListStudentsComponent

Changing from ListStudentsComponent to ListComponent fixed my issue.


p
paulsm4

I ran across this exact problem. Failed: Template parse errors: 'app-login' is not a known element... with ng test. I tried all of the above replies: nothing worked.

NG TEST SOLUTION:

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

<= I added declarations for the offending components into beforEach(.. declarations[]) to app.component.spec.ts.

EXAMPLE app.component.spec.ts

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

F
Felipe Andrade

A newbie mistake was generating the same error message in my case.

The app-root tag wasn't present in index.html


M
Meena Chaudhary

For me path for templateUrl was not correct

I was using

shopping-list-edit.component.html

Whereas it should have been

./shopping-list-edit.component.html

Silly mistake but happens when starting out. Hope that helps somebody in distress.


C
Chamila Maddumage

I had the same issue with Angular 7 when I am going to refine the test module by declaring the test component. Just added schemas: [ CUSTOM_ELEMENTS_SCHEMA ] as follows and error was solved.

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

L
Lena Tevar

For future problems. If you think you followed all the good answers and yet, the problem is there.

Try turning the server off and on.

I had the same problem, followed all the steps, couldn't solve it. Turn off, on and it was fixed.


First I thought I only had to restart npm start (under water ng serve). That sometimes helps to clear out issues. Now I had to restart Visual Studio Code entirely.
A
Auguste

OnInit was automatically implemented on my class while using the ng new ... key phrase on angular CLI to generate the new component. So after I removed the implementation and removed the empty method that was generated, the problem is resolved.


h
hoogw

Ok, let me give the details of code, how to use other module's component.

For example, I have M2 module, M2 module have comp23 component and comp2 component, Now I want to use comp23 and comp2 in app.module, here is how:

this is app.module.ts, see my comment,

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

this is m2 module:

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

My commend in code explain what you need to do here.

now in app.component.html, you can use

  <app-comp23></app-comp23>

follow angular doc sample import modul


A
Aragorn

Late answer for the thread, but I'm sure there's more people that can use this information explained in another perspective.

In Ionic, custom angular components are organized under a separate module called ComponentsModule. When the first component is generated using ionic generate component, along with the component, ionic generates the ComponentsModule. Any subsequent components gets added to the same module, rightly so.

Here's a sample 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 {}

To use the ComponentsModule in the app, like any other angular modules, the ComponentsModules needs to be imported to the AppModule. ionic generate component (v 4.12) does not add this step, so this has to be added manually.

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

d
dev'd

HUMAN ERROR - DON'T BE MISLED BY THE ERROR MESSAGE.

Why I got misled: The component I wanted to consume (ComponentA) was correctly declared in it's module (ModuleA). It was correctly exported there, too. The module (ModuleB) of the component (ComponentB) I am working in, had the import for ModuleA correctly specified. However, because of the error message being < component-a-selector > is not a known element', my entire focus was in thinking that it was a problem with ModuleA/ComponentA as that is what the error message contained; I didn't think to look at the component I was trying to consume it from. I followed every single post in every threat about this, but was ultimately missing one vital step:

What fixed it for me: frot.io's answer prompted me to check my app.module.ts import list and the component I was working in (ComponentB) was not included!


Yes, just fell into that trap. Thanks.
J
Jon Atollah

When you are declaring components in one module, exporting them, then using them in another module, you have to make sure that the module with the exports is also imported in app module. :)