Angular 2 'component' is not a known element

后端 未结 15 1969
傲寒
傲寒 2020-11-30 17:58

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: Temp

相关标签:
15条回答
  • 2020-11-30 19:02

    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 { }
    
    0 讨论(0)
  • 2020-11-30 19:04

    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!

    0 讨论(0)
  • 2020-11-30 19:05

    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.
      ],
    })
    
    0 讨论(0)
提交回复
热议问题