Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 878
WasiF Avatar asked Jan 31 '26 04:01

WasiF


1 Answers

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

like image 54
user776686 Avatar answered Feb 01 '26 19:02

user776686



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!