Quantcast
Channel: Stories by Flaha on Medium
Viewing all articles
Browse latest Browse all 85

Beam Me Up, Scotty — On Teleporting Templates in Angular

$
0
0

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 from the template and call detectChanges. 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!


Beam Me Up, Scotty — On Teleporting Templates in Angular was originally published in Netanel Basal on Medium, where people are continuing the conversation by highlighting and responding to this story.


Viewing all articles
Browse latest Browse all 85

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>