Search code examples
angulardynamic-components

How to create dynamic components using service without ComponentFactoryResolver as it is deprecated in angular


As you may know in earlier versions of angular, dynamic components could be created with the help of ComponentFactoryResolver as

export class DialogService {
  dialogComponentRef: ComponentRef<DialogComponent>

  constructor(
    private componentFactoryResolver: ComponentFactoryResolver,
    private appRef: ApplicationRef,
    private injector: Injector
  ) {}

  appendDialogComponentToBody() {
     // logic to add component using `ComponentFactoryResolver` instance
  }
}

but now ComponentFactoryResolver is deprecated for latest versions.

Yeah there is a way (so far I know) we can create dynamic components with the following snippet

@ViewChild("viewContainerRef", { read: ViewContainerRef }) vcr!: ViewContainerRef;

but again this only works within the component, not with service.

Any help would be appreciated.


Solution

  • You should be able to use the createComponent function exported from @angular/core,

    const componentRef = createComponent(MyComponent, {
      environmentInjector: this.appRef.injector,
    })
    

    then

    this.appRef.attachView(componentRef.hostView); // and detach later
    

    and you should be good to go without viewContainerRef

    Docs