As frontend developers, we have a large set of tools for creating UI components in different approaches (aiming to choose the best one taking performance into account, readability, etc..)

When developing with a framework (as for 2019 we’re still using frameworks and currently I favor Angular..) we have set of abstractions in which we should use in a certain way in order to use the maximum of the framework and without abusing the framework → in other words following its “best practices”.

In Angular when you want to dynamically render a component or template somewhere you have several techniques to do so:

Programmatically be using the ComponentFactoryResolver service:

const factory = this.resolver.resolveComponentFactory(NewAwesomComponent);

this.componentRef = this.viewContainerRef.createComponent(factory);

By using the *ngComponentOutlet or *ngTemplateOutlet structural directives

or structural directives ** By projecting content to another host using <ng-content> (not exactly dynamic but it will render in another host and not where it registered lexically so pay attention so it won't bite you).

Whenever I used *ngComponentOutlet, the fact I had to import the components I wanted to dynamically render into the hosted component felt a bit wrong, the hosted component became aware of the dynamic components it had to render thus they became coupled.

Portals to the rescue:

What if I only want my host component to have a placeholder/slot in which I could render another component without the need to explicitly import and refer it from the host template?

“use the platform” (lol)

Angular’s components dev kit — at the moment, I don’t see any reason not to use it on my projects, the Angular guys are doing a great job on maintaining it, it’s easy to use, quickly supplies a set of UI component built in a coding standard I appreciate.

So where was I when the portals came out? shutting my eyes cause using ComponentFactoryResolver is so much fun…

The official definition of a portal is:

A Portal is a piece of UI that can be dynamically rendered to an open slot on the page.

(similar to the concept of WC slot element just that the portable view isn’t a new DOM tree).

It’s pretty straight forward, so let’s see it in use: