Sitemap
Netanel Basal

Learn development with great articles

Follow publication

Beam Me Up, Scotty — On Teleporting Templates in Angular

--

In this article, I want to discuss an interesting problem I recently came across, and the solution I came up for it. Imagine the following layout:

We have the application navigation bar component at the top of the page, and we render a third-party directive inside the current page. In my case, the directive is a wrapper for a graph library.

The product requirement is to add an export button for our graph in the navigation component:

As you can probably imagine, we have an issue. We don’t have access to the directive’s API that exposes the export method from the navigation component. One solution would be to manage this whole operation with events, but it’s a bit overkill and not reusable.

If we think about it, logically, the button‘s template belongs to this component. But from a technical point of view, it would be preferable to move this part somewhere else in the DOM, outside this component. Or in other words, we want to teleport this template to another place in the DOM while keeping its context where it’s defined.

So what if we could just do the following:

Let’s create a teleportTo directive that takes a DOM selector and appends a template content to it:

First, we create a view using ViewContainerRef. Next, we obtain a reference to the host element. The viewRef exposes the rootNodes property, which contains the view’s DOM nodes; so finally, we loop over those nodes and append each one to the host.

You can also use the Portal feature from Angular Material to achieve the same thing, but I prefer not using a 3rd party tool when I don’t have to, and it’s always good to know how something works under the hood.

🚀 In Case You Missed It

Here are a few of my open source projects:

  • Akita: State Management Tailored-Made for JS Applications
  • Spectator: A Powerful Tool to Simplify Your Angular Tests
  • Transloco: The Internationalization library Angular
  • Forms Manager: The Foundation for Proper Form Management in Angular
  • Cashew: A flexible and straightforward library that caches HTTP requests

And many more!

Follow me on Medium or Twitter to read more about Angular, Akita and JS!

--

--

Netanel Basal
Netanel Basal
Netanel Basal
Netanel Basal

Written by Netanel Basal

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.

Responses (2)