Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 918
Cameron Yick Avatar asked Sep 03 '18 19:09

Cameron Yick


3 Answers

"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>
like image 113
xiaoke Avatar answered Sep 20 '22 11:09

xiaoke


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

like image 20
Francesco Marocchi Avatar answered Sep 20 '22 11:09

Francesco Marocchi


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

<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>
like image 33
GMKHussain Avatar answered Sep 23 '22 11:09

GMKHussain