DEV Community

Cover image for Dynamic UI with CDK TemplatePortal and DomPortalHost
Juri Strumpflohner for Angular

Posted on • Updated on • Originally published at

Dynamic UI with CDK TemplatePortal and DomPortalHost

Ever wanted to place some piece of UI dynamically from one component to another? But the component that owns the content doesn't have any connection to the component that should display the content. In this article we'll learn how we can leverage Angular CDK Portals for achieving exactly that.

Let's assume we have this simple (mobile-like) application.

App Home Screen

As you can see we have a toolbar with the side-bar menu button and application title, and a central area, currently displaying the home app screen. When the user clicks the menu, he/she can navigate to different screens as you might expect. Each of these screens (i.e. our routed components) has a set of specific actions. Whenever the routed component gets activated, we'd like to display those actions (lets call them page actions) inside our application's toolbar. This is a common scenario especially in mobile apps.

Note the "add" icon at the top-right of our toolbar.

Now, from a "componentization" point of view, we have some kind of ShellComponent which creates the overall layout including the toolbar, the sidebar (both of which could also be separate components) as well as a central area where our routed components will be placed. That said, the routed components don't have any knowledge where they're placed. We don't want to have a hard-coded reference to the toolbar or whatsoever.

Basically in our specific demo app,

  • the ContactListComponent does not have any knowledge of the toolbar. It might reside in a different (even lazy loaded) Angular module. Also, we wouldn't want to couple them together.
  • The displayed action is context specific though, meaning if we click the "+" button, some function on our ContactListComponent gets triggered.

Read more »

Top comments (0)