ng-content vs. ng-template

12.1k views Asked by At

What is the difference between ng-content and ng-template, and what are some different use-cases for each of them?

2

There are 2 answers

0
Ploppy On BEST ANSWER

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.

0
Kavinda Senarathne On
  1. <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.

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