What is the difference between ng-content and ng-template, and what are some different use-cases for each of them?
ng-content vs. ng-template
12.1k views Asked by geraktOfRivia At
2
There are 2 answers
0
On
<ng-template>
As the name suggests the <ng-template
> is a template element that Angular uses with structural directives (*ngIf
, *ngFor
, [ngSwitch]
and custom directives).
These template elements only work in the presence of structural directives. Angular wraps the host element (to which the directive is applied) inside <ng-template>
and consumes the <ng-template>
in the finished DOM by replacing it with diagnostic comments.
<ng-content>
They are used to create configurable components. This means the components can be configured depending on the needs of its user. This is well known as Content Projection. Components that are used in published libraries make use of <ng-content>
to make themselves configurable.
ng-content
is used to project content at a specific place within a component.Example:
The code above would produce the following html:
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:
But this one would display the
div
: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.