Angular组件调用异常:cvy-header仅在app.component可用
问题解决:ElectricalsComponent无法使用组件
问题原因
你当前仅以数组形式导出共享组件,虽然在AppModule的declarations中注册了这些组件,但如果ElectricalsComponent属于懒加载特性模块(比如独立的PagesModule),或者其所在模块未正确引入共享组件,就会出现组件无法识别的错误。而AppComponent属于AppModule,因此能正常使用
解决步骤
1. 将共享组件重构为标准SharedModule
把shared.component.ts改成Angular模块,让其他模块可通过导入它复用组件:
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HeaderComponent } from './header/header.component'; import { SideBarComponent } from './side-bar/side-bar.component'; @NgModule({ declarations: [ HeaderComponent, SideBarComponent ], imports: [ CommonModule ], exports: [ // 导出组件,供其他模块使用 HeaderComponent, SideBarComponent ] }) export class SharedModule { }
2. 修改AppModule,导入SharedModule
移除declarations中的...sharedComponent,改为在imports数组中导入SharedModule:
import { NgModule } from '@angular/core'; import { BrowserModule, provideClientHydration } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { LoginComponent } from './pages/login/login.component'; import { ElectricalsComponent } from './pages/pages/electricals.component'; // 导入重构后的SharedModule import { SharedModule } from './pages/shared/components/shared.module'; @NgModule({ declarations: [ AppComponent, LoginComponent, ElectricalsComponent, ], imports: [ BrowserModule, AppRoutingModule, SharedModule // 添加到导入列表 ], providers: [ provideClientHydration() ], bootstrap: [AppComponent], }) export class AppModule { }
3. 给ElectricalsComponent所在模块导入SharedModule
如果ElectricalsComponent属于独立的特性模块(比如PagesModule),需在该模块的imports中也导入SharedModule:
// 示例:pages.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ElectricalsComponent } from './pages/electricals.component'; import { SharedModule } from '../shared/components/shared.module'; @NgModule({ declarations: [ElectricalsComponent], imports: [ CommonModule, SharedModule // 导入共享模块 ] }) export class PagesModule { }
验证
完成以上修改后重启项目,ElectricalsComponent中的<cvy-header>即可正常渲染。
内容的提问来源于stack exchange,提问作者Yasik raam
相关产品推荐
相关产品推荐

