Dynamically create an Angular component and add it to the DOM
It is difficult to find good documentation on how to dynamically/programmatically instantiate an Angular component and add it to the DOM tree. This process is not as straightforward as one might hope.
I have created a “simple” service that encapsulates all that logic. See the code below. I annotated it with some comments to make it easier to understand what’s going on.
And here is how you would use it. First, you need to add the service to the list of
providers in your
@NgModule, as well as add your dynamic component to the list of
entryComponents on the same module:
Then, you can inject the
ComponentFactoryService anywhere in your app and call
createComponent passing the type of the component that you want to create, and optionally the location in the DOM tree:
Common use case
Perhaps the most common use case for dynamic components is modals (dialogs, panels, notifications). If you’re looking for a complete and ready to use solution for modals, or want to see an example how the above code is used for this purpose, check out ind-modal — a lightweight implementation of modal dialogs/panels for Angular.
Originally published at www.pglazkov.com on October 16, 2017.