Angular 2 'component' is not a known element

后端 未结 15 2095
傲寒
傲寒 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 18:48

    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!

提交回复
热议问题