What is the difference between ng-container, ng-template, and ng-content?

In this article, learn about ng-container, ng-template, and ng-content in angular

Introduction

In the context of Angular, ng-container, ng-template, and ng-content are three different Angular directives that serve different purposes. Let's explore each one:

ng-container

The ng-container directive is a non-rendered element that is used to group and manage structural directives, such as *ngIf, *ngFor, etc. It acts as a placeholder or wrapper for these structural directives when they need to be applied to multiple elements or when you want to use them without adding an additional DOM element. The ng-container itself doesn't create any extra elements in the final DOM, making it a useful tool for organizing and applying structural directives without affecting the layout.

<ng-container *ngIf="condition">
  <!-- Elements to show when the condition is true -->
</ng-container>

ng-template

The ng-template directive defines an Angular template that can be used to encapsulate HTML markup and Angular code that won't be rendered immediately. It acts as a template placeholder and can be referenced using the *ngTemplateOutlet directive or by using the <ng-container> element with the *ngTemplateOutlet attribute. ng-template is particularly useful when you want to reuse a piece of HTML code with its associated logic in multiple places.

<ng-template #myTemplate>
  <!-- Template content here -->
</ng-template>

<ng-container *ngTemplateOutlet="myTemplate"></ng-container>

ng-content

The ng-content directive is used to create content projection slots within a component. It allows you to pass content from the parent component to the child component's template. When you define <ng-content></ng-content> in the child component's template, it acts as a placeholder for the content that will be projected into it from the parent component.

Example. Parent Component Template.

<app-child>
  <!-- Content to project into the app-child component -->
</app-child>

As per the above snippet, the content is within the <app-child> tag.

Happy learning :)