使用<ng-content>无法将<p-tabPanel>投影到PrimeNG <p-tabView>的问题
问题解决步骤
1. 移除不必要的组件继承
ChildTabViewComponent不需要继承BaseTabViewComponent——它只是在模板中嵌套使用<app-base-tab-view>,组件类的继承在这里没有实际作用,反而可能造成逻辑混淆。修改后的子组件代码:
import { Component } from '@angular/core'; @Component({ selector: 'app-child-tab-view', template: ` <app-base-tab-view> <p-tabPanel header="Child Tab 1"> <div>Content for Child Tab 1</div> </p-tabPanel> <p-tabPanel header="Child Tab 2"> <div>Content for Child Tab 2</div> </p-tabPanel> </app-base-tab-view> `, }) export class ChildTabViewComponent { // 无需继承,也不需要super()调用 }
2. 确保TabViewModule在组件所在模块中导入
即使AppModule中已经导入TabViewModule,如果BaseTabViewComponent或ChildTabViewComponent属于某个Feature模块,该模块必须单独导入TabViewModule,或者通过SharedModule共享:
方式一:在Feature模块中直接导入
假设组件属于TabModule:
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { TabViewModule } from 'primeng/tabview'; import { BaseTabViewComponent } from './base-tab-view.component'; import { ChildTabViewComponent } from './child-tab-view.component'; @NgModule({ declarations: [BaseTabViewComponent, ChildTabViewComponent], imports: [ CommonModule, TabViewModule // 必须在此处导入,确保组件能获取TabView的提供者 ], exports: [BaseTabViewComponent, ChildTabViewComponent] }) export class TabModule { }
方式二:通过SharedModule共享
如果多个模块需要使用PrimeNG组件,可创建SharedModule统一管理:
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { TabViewModule } from 'primeng/tabview'; @NgModule({ imports: [CommonModule, TabViewModule], exports: [TabViewModule] // 导出后,其他模块导入SharedModule即可使用TabView }) export class SharedModule { }
3. 验证效果
完成上述修改后,<app-child-tab-view>将正常显示所有标签页:
- 固定的「Common Tab」
- 自定义的「Child Tab 1」和「Child Tab 2」
问题根源解释
之前的NullInjectorError会阻止PrimeNG的TabView组件完成初始化,导致<ng-content>中的TabPanel无法被识别和渲染。解决提供者问题后,TabView能正常工作,所有嵌套的TabPanel都会被加载。
内容的提问来源于stack exchange,提问作者imnotthatrobot
相关产品推荐
相关产品推荐

