Angular报错:'router-outlet'不是已知元素,请求排查问题
Angular报错:'router-outlet' is not a known element 问题排查
你的代码核心问题是ProductsComponent未在ProductsModule的declarations数组中声明,具体原因和修复方式如下:
问题分析
- ProductsComponent作为路由组件被配置在
products-routing.module.ts中,同时它的模板products.component.html里使用了<router-outlet>指令,但该组件没有被纳入ProductsModule的声明列表。 - Angular要求所有组件必须在所属模块的
declarations中声明,才能编译其模板并识别其中的指令(包括RouterModule提供的router-outlet、routerLink等)。虽然ProductsModule导入了ProductsRoutingModule(间接导入RouterModule),但未声明ProductsComponent的话,模板里的指令无法生效。
修复方案
修改products.module.ts,将ProductsComponent添加到declarations数组中:
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { LaptopComponent } from './laptop/laptop.component'; import { MobileComponent } from './mobile/mobile.component'; import { ProductsRoutingModule } from './products-routing.module'; // 导入ProductsComponent import { ProductsComponent } from './products.component'; @NgModule({ imports: [CommonModule, ProductsRoutingModule], declarations: [ ProductsComponent, // 添加该组件到声明列表 LaptopComponent, MobileComponent ], }) export class ProductsModule {}
修改后,Angular会正确编译ProductsComponent的模板,<router-outlet>指令也能被正常识别,报错即可解决。
内容的提问来源于stack exchange,提问作者Tanzeel
相关产品推荐
相关产品推荐

