Adventures in Angular Upgrading — Part 2

Friday, 28th of July

Jon Rimmer
Jul 28, 2017 · 2 min read

I thought that when you declared a template reference variable using the #myForm or #myForm="ngForm" that variable was available anywhere in the template. I don’t know why I thought this, probably because the Angular documentation says:

“The scope of a reference variable is the entire template. Do not define the same variable name more than once in the same template. The runtime value will be unpredictable.”

Well, it turns out there’s an important caveat to that: If the variable is declared within the scope of an *ngIf then it’s unavailable outside. This is apparently by design.


One of the nicest things about React’s approach to components is that it gives you very precise control over the rendered HTML and, if needed, a component can render nothing other than its children. This means you can have a deeply nested hierarchy of components, but actually emit a very simple, shallow DOM tree.

These kind of simple, shallow DOM is very helpful for styling with CSS. Since every element in the DOM produces a CSS box by default, it complicates using layouts like flexbox when you have a deeply nested hierarchy. The CSS solution for this is display: contents, but that won’t be available in all browsers for a while yet.

While Angular can’t boast a React level of control, I’ve found recently that that <ng-container> goes a long way to closing the gap. This element exists in the template only, and never emits anything into the DOM. The result is that you can use it to apply any number of complex structural directives, while keeping the rendered HTML to a minimum.

For example, consider the common case of wanting an *ngFor to produce a set of <tr>’s, instead of just one. Since you cannot use elements like <div> in a table, it isn’t possible to create a “real” wrapper element. But it’s trivially achievable with <ng-container>:

<table>
<ng-container *ngFor="item row of items">
<tr> ... </tr>
<tr> ... </tr>
<tr> ... </tr>
</ng-container>
</table>
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade