发布于 2021-02-07 14:01:44
我解决了这个问题。基本上,它将停止CreateDynamicComponentService在TabView组件中的递归foreach循环,在TabView中设置一个制表符变量,并从服务中重新启动递归函数:
create-dynamic-component.service
createComponent(content: any, type: any, vcRef) {
const componentRef = this.renderComp(content, type, vcRef)
if (content.nodes && content.nodes.length) {
if (!componentRef.instance.embeddedContainer) {
const cmpName = componentRef.instance.constructor.name;
if (cmpName != 'TabViewComponent') {
throw new TypeError('Trying to render embedded content. ${cmpName} must have @ViewChild() embeddedContainer defined');
}
} else {
content.nodes.forEach(type => {
const typeP = this.contentMappings[type.type];
this.createComponent(type, typeP, componentRef.instance.embeddedContainer);
});
}
}
}
TabViewComponent
@Component({
selector: 'dynamic-page-tab-view',
template: '<p-tabView dynamic="true" cache="false">
<p-tabPanel [header]="tab.header" *ngFor="let tab of tabs; let i = index" [selected]="i == 0">
{{ tab.header }}
<ng-container #panel></ng-container>
</p-tabPanel>
</p-tabView>'
})
export class TabViewComponent implements AfterViewInit {
@ViewChild('container', { read: ViewContainerRef, static: true })
embeddedContainer: ViewContainerRef;
@ViewChildren('panel', {read: ViewContainerRef}) tabPanels: QueryList<ViewContainerRef>
activeIndex: number;
tabs: any = []
constructor(private changeDetector : ChangeDetectorRef,
private viewContainerRef: ViewContainerRef,
private createDynamicComponentService: CreateDynamicComponentService,
@Inject(CONTENT_MAPPINGS) private contentMappings: any) { }
contentOnCreate(values: { [key: string]: any; }): void {
this.tabs = values["nodes"];
this.activeIndex = 0;
}
ngAfterViewInit() {
this.tabPanels.forEach((viewRef: ViewContainerRef, index: number) => {
console.log(index, viewRef, this.tabs[index]);
const type = this.tabs[index];
const typeP = this.contentMappings[type.type];
this.createDynamicComponentService.createComponent(type, typeP, viewRef);
this.changeDetector.detectChanges();
});
}
}
重要的是,TabPanel组件只存在于单个容器中。
<ng-container #container></ng-container>
PrimeNg TabPanel本身在TabView组件中创建和模板化。
https://stackoverflow.com/questions/66079407
复制相似问题