What is the difference between ng-content and ng-template, and what are some different use-cases for each of them?
ng-content
is used to project content at a specific place within a component.
Example:
<!-- custom.component.html -->
<h1>
<ng-content></ng-content>
</h1>
<!-- app.component.html -->
<app-custom>test</app-custom>
The code above would produce the following html:
<app-custom>
<h1>
test
</h1>
</app-custom>
ng-template
is a block describing a template, a template is not rendered unless explicitly referenced or used.
The following code does not output any HTML:
<ng-template>
<div>Hello</div>
</ng-template>
But this one would display the div
:
<ng-container *ngIf="false; else myTemplate"></ng-container>
<ng-template #myTemplate>
<div>Hello</div>
</ng-template>
Both will never be visible in the HTML code, they are only used by Angular.
Bonus:
ng-container
is another Angular element used with structural directives (ngFor, ngIf), it does not produce HTML either.