The intention here is to dynamically insert a component into another…
To start with, there are HTML Elements that go inside angular Views (using Element Ref), and these views go inside View Containers ie Components (using ViewContainerRef).
Now, let’s take specific eg. of inserting pop up on button click…Now, pop-up is a component in itself, so to insert it into the DOM when HTML Button containing this [popover] directive is clicked, we need to transform the Pop-Up component into a View. To do this, we need ComponentFactoryResolver which will take the content, create view from it and inject it into the DOM.
To make things complex, let’s say that this Component to be injected dynamically has a hole ie <ng-content> that needs to be filled by the user of it…So now we pass the dynamic template to the directive [popover]=”myTemplate”. This myTemplate will replace the <ng-content> of the popover directive when it’s injected dynamically.
For this, first a EmbeddedView needs to be created from myTemplate and then the View from the actual popOver component is created with the <ng-content> hole being filled by this new EmbeddedView created in first step. Finally this popOver view is injected into the DOM.
Last use case is the creation of Views using a Service. This is useful to implement Modal widget which might be invoked from LoginService etc. The distinction here is that Services don’t have ViewContainerRef, (unlike Directives) coz they contain reference of the element they’re on and so work only for Directives, coz directives are applied exclusively on DOM Elements.
So to start with, the new View we’ll create using the service uses the same steps and apis as directive above. Only the final step ie attaching the change detection strategy to this new view, which ViewContainerRef used to do above, will now be done by the applicationRef api instead using attachView method on it.