[英]Angular: destroy dynamic component
在一個聊天應用程序上,我正在使用它來創建多個ChatComponent(作為動態組件)。
loader.service.ts
import { ChatComponent } from '../components/shared/chat/chat.component';
@Injectable()
export class LoaderService {
constructor( @Inject(ComponentFactoryResolver) factoryResolver )
{
this.factoryResolver = factoryResolver
}
setRootViewContainerRef(viewContainerRef){
this.rootViewContainer = viewContainerRef
}
addDynamicComponent(timeIdentifier){
const factory = this.factoryResolver.resolveComponentFactory(ChatComponent);
const component = factory.create(this.rootViewContainer.parentInjector)
component.instance.timeIdentifier = timeIdentifier;
this.rootViewContainer.insert(component.hostView)
}
}
chat-container.component.ts
export class ChatContainerComponent implements OnInit {
@ViewChild('chat', { read: ViewContainerRef }) viewContainerRef: ViewContainerRef
constructor( protected loaderService: LoaderService, protected route: ActivatedRoute ) { }
ngOnInit() {
this.route.params.subscribe(params => {
this.loaderService.setRootViewContainerRef(this.viewContainerRef)
this.loaderService.addDynamicComponent(params['timeIdentifier'])
});
}
}
這樣,我可以生成多個“ ChatComponent”作為動態組件。
但是一旦創建它們,我如何銷毀它們呢?
編輯
我已經在ChatComponent中添加了此內容(由組件工廠創建)
this.cmpRef.destroy();
但是當我打電話給我時,我陷入了無限循環,出現了如下錯誤:
ERROR RangeError: Maximum call stack size exceeded
從工廠創建的組件的類型為ComponentRef
。 此類具有destroy
功能,可以銷毀實例和關聯的結構。
在此處檢查: https : //angular.io/api/core/ComponentRef
我找到了銷毀組件的更好方法,您可以執行以下操作:
addDynamicComponent(timeIdentifier){
const factory = this.factoryResolver.resolveComponentFactory(ChatComponent);
const component = factory.create(this.rootViewContainer.parentInjector)
component.instance.timeIdentifier = timeIdentifier;
component.instance.autodestroy = () => component.destroy();
this.rootViewContainer.insert(component.hostView)
}
在組件類中,您將創建一個方法autodestroy
,並在您想要銷毀它時調用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.