gpt4 book ai didi

angular - 如何检查组件是否已存在于 viewContainerRef Angular 中

转载 作者:行者123 更新时间:2023-12-05 08:08:29 27 4
gpt4 key购买 nike

我是这样动态添加组件的:

export class CustomersOverviewComponent implements OnInit, OnDestroy {

@ViewChild(PanelDirective) customerHost: PanelDirective;

constructor(private componentFactoryResolver: ComponentFactoryResolver, private sidebarService: SidebarService) {

}

ngOnDestroy(): void {

}

ngOnInit(): void {
console.log('init');

this.sidebarService.currentAddPanel.subscribe(panel => {
if (panel instanceof PanelItem) {
this.loadcomponent(panel);
}
});
}

loadcomponent(panel: PanelItem): void {
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(panel.component);
let viewContainerRef = this.customerHost.viewContainerRef;

console.log('viewcontainer', viewContainerRef);
console.log('element', viewContainerRef.element);

let componentRef = viewContainerRef.createComponent(componentFactory);

(<IPanel>componentRef.instance).data = panel.data;
(<IPanel>componentRef.instance).self = componentRef;
}


}

但是在向 viewContainer 添加新组件之前,我想遍历它并检查我的组件是否已经存在。我该怎么做?

我在 viewContainerRef 中看不到任何可循环的属性。

最佳答案

就不能直接在本地赋值吗?

loadcomponent(panel: PanelItem): void {
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(panel.component);
let viewContainerRef = this.customerHost.viewContainerRef;

if (!this.componentRef) {
this.componentRef = viewContainerRef.createComponent(componentFactory);
}

(<IPanel>this.componentRef.instance).data = panel.data;
(<IPanel>this.componentRef.instance).self = this.componentRef;

关于angular - 如何检查组件是否已存在于 viewContainerRef Angular 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48949222/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com