[angular] Angular 2 'component' is not a known element

I'm trying to use a component I created inside the AppModule in other modules. I get the following error though:

"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.

My project structure is quite simple: Overall project structure

I keep my pages in pages directory, where each page is kept in different module (e.g. customers-module) and each module has multiple components (like customers-list-component, customers-add-component and so on). I want to use my ContactBoxComponent inside those components (so inside customers-add-component for example).

As you can see I created the contacts-box component inside the widgets directory so it's basically inside the AppModule. I added the ContactBoxComponent import to app.module.ts and put it in declarations list of AppModule. It didin't work so I googled my problem and added ContactBoxComponent to export list as well. Didn't help. 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.

What am I missing?

This question is related to angular typescript angular-components angular-module

The answer is


These are the 5 steps I perform when I got such an error.

  • Are you sure the name is correct? (also check the selector defined in the component)
  • Declare the component in a module?
  • If it is in another module, export the component?
  • If it is in another module, import that module?
  • Restart the cli?

When the error eccors during unit testing, make sure your declared the component or imported the module in 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.

You can't declare a component twice. You should declare and export your component in a new separate module. Next you should import this new module in every module you want to use your component.

It is hard to tell when you should create new module and when you shouldn't. I usually create a new module for every component I reuse. When I have some components that I use almost everywhere I put them in a single module. When I have a component that I don't reuse I won't create a separate module until I need it somewhere else.

Though it might be tempting to put all you components in a single module, this is bad for the performance. While developing, a module has to recompile every time changes are made. The bigger the module (more components) the more time it takes. Making a small change to big module takes more time than making a small change in a small module.


I have the same issue width php storm version 2017.3. This fix it for me: intellij support forum

It was an error width @angular language service: https://www.npmjs.com/package/@angular/language-service


I had the same problem with Angular CLI: 10.1.5 The code works fine, but the error was shown in the VScode v1.50

Resolved by killing the terminal (ng serve) and restarting VScode.


Route modules (did not saw this as an answer)

First check: if you have declared- and exported the component inside its module, imported the module where you want to use it and named the component correctly inside the HTML.

Otherwise, you might miss a module inside your routing module:
When you have a routing module with a route that routes to a component from another module, it is important that you import that module within that route module. Otherwise the Angular CLI will show the error: component is not a known element.

For example

1) Having the following project structure:

+---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) Inside the todos-routing.module.ts you have a route to the edit.todo.component.ts (without importing its module):

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

The route will just work fine! However when importing the sidebar.module.ts inside the edit-todo.module.ts you will get an error: app-sidebar is not a known element.

Fix: Since you have added a route to the edit-todo.component.ts in step 2, you will have to add the edit-todo.module.ts as an import, after that the imported sidebar component will work!


A lot of answers/comments mention components defined in other modules, or that you have to import/declare the component (that you want to use in another component) in its/their containing module.

But in the simple case where you want to use component A from component B when both are defined in the same module, you have to declare both components in the containing module for B to see A, and not only A.

I.e. in 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.
  ],
})

Supposedly you have a component:

product-list.component.ts:

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

And you get this error:

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';
}

Make sure you import the component:

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

I had a similar issue. It turned out that ng generate component (using CLI version 7.1.4) adds a declaration for the child component to the AppModule, but not to the TestBed module that emulates it.

The "Tour of Heroes" sample app contains a HeroesComponent with selector app-heroes. The app ran fine when served, but ng test produced this error message: 'app-heroes' is not a known element. Adding the HeroesComponent manually to the declarations in configureTestingModule (in app.component.spec.ts) eliminates this error.

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

This convoluted framework is driving me nuts. Given that you defined the custom component in the the template of another component part of the SAME module, then you do not need to use exports in the module (e.g. app.module.ts). You simply need to specify the declaration in the @NgModule directive of the aforementioned module:

// app.module.ts

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

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

You do NOT need to import the JsonInputComponent (in this example) into AppComponent (in this example) to use the JsonInputComponent custom component in AppComponent template. You simply need to prefix the custom component with the module name of which both components have been defined (e.g. app):

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

Notice app-json-input not json-input!

Demo here: https://github.com/lovefamilychildrenhappiness/AngularCustomComponentValidation


I am beginning Angular and in my case, the issue was that I hadn't saved the file after adding the 'import' statement.


In my case, my app had multiple layers of modules, so the module I was trying to import had to be added into the module parent that actually used it pages.module.ts, instead of app.module.ts.


I got the same issue, and it was happening because of different feature module included this component by mistake. When removed it from the other feature, it worked!


The problem in my case was missing component declaration in the module, but even after adding the declaration the error persisted. I had stop the server and rebuild the entire project in VS Code for the error to go away.


I was facing the same issue. In my case I have forgotten to declare Parent component in the app.module.ts

As a example if you are using <app-datapicker> selector in ToDayComponent template, you should declare both ToDayComponent and DatepickerComponent in the app.module.ts


I just had the exact same issue. Before trying some of the solutions posted here, you might want to check if the component really doesn't work. For me, the error was shown in my IDE (WebStorm), but it turned out that the code worked perfectly when i ran it in the browser.

After I shut down the terminal (that was running ng serve) and restarted my IDE, the message stopped showing up.


I know this is a long resolved problem, but in my case I had a different solution. It was actually a mistake I made that maybe you made as well and didn't fully notice. My mistake was that I accidentally placed a Module e.g., MatChipsModule, MatAutoCompleteModule, on the declarations section; the section that is composed only by components e.g., MainComponent, AboutComponent. This made all my other import unrecognizable.


This question may seem old and odd, but when I was trying to load a module(lazy loading) and getting the same error, I realized I was missing an exports clause for the component that shipped as a part of a larger module.

This Angular.io Link explains why: Components/Services inside a module, remains private(or protected) by default. To make them public, you have to export them.

Expanding on @Robin Djikof's answer with @live-love code sample, this is what was technically missing in my case(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 { }

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to angular-components

How to rename a component in Angular CLI? How to Update a Component without refreshing full page - Angular Angular 2 'component' is not a known element How to get element's width/height within directives and component? Call child component method from parent class - Angular How to style child components from parent component's CSS file? What is the equivalent of ngShow and ngHide in Angular 2+? Angular 2: How to style host element of the component? How can I select an element in a component template?

Examples related to angular-module

Angular 2 'component' is not a known element Use component from another module What is the difference between declarations, providers, and import in NgModule?