Getting to Know the createApplication API in Angular
Angular v14.2.0 introduce a new function named createApplication
. The createApplication
function creates an application instance without bootstrapping any components.
It is useful when one wishes to decouple or delay the rendering of components and/or render multiple root components in one application.
Custom element types can be created using this API and linked to an application’s environment. Let’s see it in action:
The createApplication()
function takes a list of providers
that should be available to the root component and all its children and returns a promise that returns an ApplicationRef
. This allows the creation of multiple component instances with different injectors trees.
We can then add a custom element to the page using the environment injector. We can also destroy this application by calling the appRef.destroy()
method.
Now let’s say we have the following component:
We can create an isolated application and add it to our page:
First, we obtain a reference to NgZone
so that we can create the component within Angular’s zone. Next, we use the createComponent
function, passing the injector
and a host
element. The last step is registering the newly created ref using the ApplicationRef
instance to include the component view in change detection cycles.
This thread describes one use case for this API:
Follow me on Medium or Twitter to read more about Angular and JS!