ngContainer vs ngContent

 

Angular 2+ does not allow us to use more than one structural directives on a html element. The best way to work around this is to move each structural directive to its own html element. For example the below will throw an error:

<ul *ngIf="true" *ngFor="let item of items">

<li>item.name</li>

</ul>


This is because under the hood angular places each * structural directive in a ng-template and this scenario would confuse it. So one possible solution is to move them to separate html elemnts like:


<div *ngIf="true" >

<ul *ngFor="let item of items">

<li>item.name</li>

</ul>

</div>


But this means that the css would need to be adjusted to account for another div. So angular provides an element that does not generate any html, this element is ng-content. The way to use is:


<ng-container *ngIf="true" >

<ul *ngFor="let item of items">

<li>item.name</li>

</ul>

</ng-container>


So ng-container is a grouping element that doesn't interfere with the styles or layout of the page. ng-content on the other hand is used for transclusion / content projection. So say we had a stylish display component, that had some custom styling for displaying a panel and take a header and message, it would look like:


@Component({ selector: 'stylish-panel',

template: `

<div class="stylish-panel">

<div class="header">

<ng-content select="header"></ng-content>

</div>

<div class="message">

<ng-content select="message">

</ng-content>

</div>

</div>

`});

 

Then we could transclude content into our stylish panel and even use this component mulitple times to get the same style in multiple locations across the site, like:

<div class="customer-reviews">

<stylish-panel>

<span header>Customer 1</span>

<span message>Where are my chips?</span>

</stylish-panel>

<stylish-panel>

<span header>Customer 2</span>

<span message>Your store was awesome!</span>

</stylish-panel>

<stylish-panel>

<span header>Customer 3</span>

<span message>We found what we were looking for</span>

</stylish-panel>

</div>

Hopefully the differences and uses of the two are visible now

Schubert

Other topics you might like: