[Fixed] Is there an Angular 2+ Equivalent to React Fragments?

Issue

I would like to extract a portion of a component without actually creating an additional “wrapper” element in the physical DOM, because it breaks my CSS.

Example: I noticed a section in my HTML template that looks like this:

<div>Foo</div>
<div>Bar</div>

I want extract these two tags into a component called <MyComponent>, and reuse it in other places. However, when I don’t actually want a parent component called <MyComponent> to be added to the DOM. Currently what I see rendered is

<MyComponent>
  <div>Foo</div>
  <div>Bar</div>
</MyComponent>

React lets me solve this problem perfectly using the concept of a Fragment component, which lets you group elements without adding an additional node to the DOM.

I am wondering if there is a section of the Angular Component API that I’m missing that will let me do this, or it there’s a fundamentally different way I should be thinking about reusing code within Angular Components.

This application is in Angular 6, and I’m coming from a background in React 16+.

Edited with Sample Code Snippet: I would like this to render without having a hello element added to the DOM – I only want the <p> tag inside the hello component to appear

https://stackblitz.com/edit/angular-kaxm27

Solution

“ng-container” is an element that’s available in Angular 2+ and that can act as the host to structural directives.

<ng-container> 
  <div>Foo</div>
  <div>Bar</div>
</ng-container>

Leave a Reply

(*) Required, Your email will not be published