Is there an Angular 2+ Equivalent to React Fragments?

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

“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>

You can do like this:

@Component({
  // tslint:disable-next-line: component-selector
  selector: '[my-fragment-component]',
  ...
})
export class MyFragmentComponent {}

<div my-fragment-component>
</div>

It will work, don’t know of any possible side-effects…

Usage ng-container with ngFor ( for ) loop and table tag.

Read More:   Why declare properties on the prototype for instance variables in JavaScript

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Title</th>
    </tr>
  </thead>
  <tbody>
   <ng-container *ngFor="let item of items">
    <tr>
      <td>{{ item.id }}</td>
      <td>{{ item.title }}</td>
    </tr>
   <ng-container>
  <tbody>
</table>

At the time of this writing, this feature does not appear to be directly supported. Some commenters have indicated this is possible with the help of some low-level APIs, but I haven’t found a working code sample yet.

There is an open feature request in the Angular Github repository with active discussion around figuring out how to add this for a future release (after Angular 6).

Further reading from the Github repository:


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts