首页 > 解决方案 > Angular 11 - RouterModule - 'router-outlet' 不是已知元素

问题描述

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

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

    src/app/gardening/gardening/gardening.component.html:5:1 - error NG8001: 'router-outlet' is not a known element:
1. If 'router-outlet' is an Angular component, then verify that it is part of this module.
2. If 'router-outlet' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

5 <router-outlet></router-outlet>
  ~~~~~~~~~~~~~~~

  src/app/gardening/gardening/gardening.component.ts:5:16
    5   templateUrl: './gardening.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component GardeningComponent.

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

这是我的 module.ts

@NgModule({
declarations: [GardeningComponent, DemogardenComponent],
imports: [
CommonModule, RouterModule
],
exports:[GardeningComponent, DemogardenComponent]

})
export class GardeningModule { }

这是我的 app.module.ts

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

怎么了,错过了什么?

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

标签: angularroutesrouter-outlet

解决方案


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

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

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

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


推荐阅读