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.
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With