3

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.

3
  • Does this answer your question? How can I inject ViewContainerRef into a service? Commented Sep 20, 2022 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 netbasal.com/… The new createComponent API, that's the replacement. Commented Sep 20, 2022 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. Commented Sep 20, 2022 at 12:32

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

2 Comments

should appRef.injector fail, that means it doesn't have all providers. In that case take the injector from the target component.
Amazing, I was wondering how to do this without needing ViewContainerRef. Didn't know they exported such a simple function to do this now

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.