I create dynamic components in an HTMLElement with the following code:
import {ApplicationRef, ComponentFactory, ComponentFactoryResolver, ComponentRef, Injector} from '@angular/core';
import {DynamicTableComponent} from '../table/dynamic-table/dynamic-table.component';
export class Table {
private readonly el: Element;
private compRef!: ComponentRef<DynamicTableComponent>;
constructor(el: Element, private resolver: ComponentFactoryResolver, private injector: Injector, private appRef: ApplicationRef) {
this.el = el;
}
public destruct(): void {
if (this.compRef !== null && this.compRef !== undefined) {
this.appRef.detachView(this.compRef.hostView);
// is done by this.compRef.destroy();
// this.compRef.instance.ngOnDestroy();
this.compRef.destroy();
}
}
public addTable(el: Element): void {
const compFactory: ComponentFactory<any> = this.resolver.resolveComponentFactory(DynamicTableComponent);
this.compRef = compFactory.create(this.injector, undefined, el);
this.appRef.attachView(this.compRef.hostView);
}
}
The component is dynamically loaded into an HTML element and added via attachView. The destruct()
method then removes the component cleanly. It´s working fine but since Angular 13 it´s deprecated. So I don´t have an ViewContainerRef and I don´t really know how to do it right in > Angular 13!?
Do you have any advice for me?
Thanks and greetings