如何在其他模块/路由中使用组件?Keypad组件调用异常求助
Hey Eric, let's break down why your Keypad Component works in MainComponent but throws a "component doesn't exist" error when used in ProductComponent inside the router-outlet—this is almost always an Angular module scoping issue, and we can fix it step by step:
1. Verify Keypad Component's Declaration & Export
First, check which module your Keypad Component belongs to (it sounds like it's in MainModule). For components to be usable outside their home module, they need to be exported:
- Open
main.module.tsand make sure:KeypadComponentis listed in thedeclarationsarray (required for the module to recognize it)KeypadComponentis added to theexportsarray (so other modules can access it)
@NgModule({ declarations: [MainComponent, KeypadComponent], exports: [KeypadComponent, RouterModule], // Export Keypad for external use imports: [RouterModule.forChild(mainRoutes)] }) export class MainModule { }
2. Import the Keypad's Module into ProductComponent's Module
If ProductComponent lives in AppModule (or another separate module like ProductModule), you need to import the module that contains and exports Keypad:
- For
AppModule:@NgModule({ declarations: [AppComponent, ProductComponent], imports: [BrowserModule, MainModule, RouterModule.forRoot(appRoutes)], // Import MainModule here bootstrap: [AppComponent] }) export class AppModule { } - If
ProductComponentis in its ownProductModule, addMainModule(or a shared module with Keypad) toProductModule'simportsarray instead.
3. Avoid Duplicate Component Declarations
Never declare KeypadComponent in more than one module! Angular enforces that a component belongs to exactly one module. If you accidentally added it to both MainModule and AppModule, this will cause conflicts and unexpected scoping issues. Stick to declaring it only in its home module (or a shared module) and importing that module elsewhere.
4. Double-Check Route Configuration
Ensure the route loading ProductComponent is set up correctly, and the module containing that route has access to Keypad's module. For example, if ProductComponent's route is defined in AppRoutingModule, AppModule must import MainModule (or the shared module) to make Keypad available to the routed component.
Bonus: Use a Shared Module for Reusable Components
If you plan to use Keypad in multiple components/modules, create a dedicated SharedModule to house it. This keeps your code organized and avoids repeated imports:
// shared.module.ts @NgModule({ declarations: [KeypadComponent], exports: [KeypadComponent] }) export class SharedModule { }
Then import SharedModule into MainModule, AppModule, or any other module that needs to use Keypad.
内容的提问来源于stack exchange,提问作者Eric Chu

