Angular 11 - RouterModule - “路由器出口”不是已知元素

Chr*_*972 4 routes router-outlet angular

我\xe2\x80\x99m是Angular的新手,目前我正在研究路由。我在组件中使用子路由时遇到了问题。routerLink\xe2\x80\x99t 在组件中呈现为链接。如果我使用路由器插座,应用程序就会崩溃。

\n

使用路由器插座我收到以下错误消息:

\n
    src/app/gardening/gardening/gardening.component.html:5:1 - error NG8001: \'router-outlet\' is not a known element:\n1. If \'router-outlet\' is an Angular component, then verify that it is part of this module.\n2. If \'router-outlet\' is a Web Component then add \'CUSTOM_ELEMENTS_SCHEMA\' to the \'@NgModule.schemas\' of this component to suppress this message.\n\n5 <router-outlet></router-outlet>\n  ~~~~~~~~~~~~~~~\n\n  src/app/gardening/gardening/gardening.component.ts:5:16\n    5   templateUrl: \'./gardening.component.html\',\n                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n    Error occurs in the template of component GardeningComponent.\n
Run Code Online (Sandbox Code Playgroud)\n

我用谷歌搜索了错误消息,解决方案始终是模块中缺少 RouterModule 的导入。我已经导入了 RouterModule。

\n

这是我的 module.ts

\n
@NgModule({\ndeclarations: [GardeningComponent, DemogardenComponent],\nimports: [\nCommonModule, RouterModule\n],\nexports:[GardeningComponent, DemogardenComponent]\n\n})\nexport class GardeningModule { }\n
Run Code Online (Sandbox Code Playgroud)\n

这是我的 app.module.ts

\n
@NgModule({\ndeclarations: [\nAppComponent\n],\nimports: [\nBrowserModule,\nAppRoutingModule\n],\nproviders: [],\nbootstrap: [AppComponent]\n})\nexport class AppModule { }\n
Run Code Online (Sandbox Code Playgroud)\n

什么\xe2\x80\x99s错了,漏掉了什么?

\n

如果您愿意,也可以查看我在 github 上的存储库中的代码: SimpleRouting

\n

Biz*_*Bob 7

我没有看到您提到的完全相同的错误,但我看到其他与缺少导入有关的问题。

Home由于和都有单独的模块Gardening,因此您还需要将它们导入到您的app.module.ts文件中:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,   
    GardeningModule,    // <------
    HomeModule          // <------
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

经过这两个小更改后,您的代码可以正常工作。(正在使用StackBlitz