2

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.

WasiF
  • 26,101
  • 16
  • 120
  • 128
  • Does this answer your question? [How can I inject ViewContainerRef into a service?](https://stackoverflow.com/questions/40636840/how-can-i-inject-viewcontainerref-into-a-service) – skink Sep 20 '22 at 11:39
  • 1
    As long as you stay in Angular 13, it's okay to keep using the "deprecated way". The replacement is only available in 14.1 Please have a look here https://netbasal.com/getting-to-know-the-createcomponent-api-in-angular-22fb115f08e2 The new createComponent API, that's the replacement. – WSD Sep 20 '22 at 11:41
  • 1
    @shrink actually your provided is required to have component already exist but think of an angular material dialog, you just create the dialog-component only through a service. – WasiF Sep 20 '22 at 12:32

1 Answers1

4

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

user776686
  • 7,933
  • 14
  • 71
  • 124
  • should appRef.injector fail, that means it doesn't have all providers. In that case take the injector from the target component. – user776686 May 13 '23 at 14:22
  • Amazing, I was wondering how to do this without needing `ViewContainerRef`. Didn't know they exported such a simple function to do this now – Mark Thompson Aug 12 '23 at 15:16