In this blog, we are going to explore the most important features of angular. We will explore ng-template
ng-container
ngTemplateOutlet
Let’s explore each feature one by one.
1. ng-template
<ng-template>
is used to render ng-template
[ngIf]
Let’s create our first ng-template
like this showing below:
So the complete code will be like:
app.component.html
Notice the line 5, we have created our first ng-template
, and now run the app in the browser and see the output.

Hey, but where is my template? I don’t see it here. The reason being is <!---->

Let’s try to understand few things about <ng-template>
.
What is <ng-template> in Angular?
<ng-template>
is a virtual element and its contents are displayed only when used along with structural directiveslike [ngIf]
, [ngFor]
and [ngSwitch]
. That’s why our template doesn’t show up inabove example.
<ng-template>
is not exactly a true web element. When we compile our code, we will not see our a<ng-template>
in our HTML DOM.
- Without any structural directive, Angular will compile the
<ng-template>
element into comment section in HTML DOM.
Now, let’s see how to display our <ng-template>
in our web page using [ngIf]
.
Using <ng-template> with [ngIf] directive
To display our template, simply we will [ngIf]
app.component.html
app.component.ts
Now, it will display our ng-template
content on our web page.

Using <ng-template> with [ngFor] directive
Let’s move forward, and see how we can use <ng-template>
[ngFor]
app.component.ts
In the above code, we have created Employees
<ng-template>
[ngFor]
2. ng-container
Let’s see the case, where we can ng-container
ngIf
ngFor
in
Here in the above code, we have ngIf
ngFor
on

It is saying, you can’t have multiple template bindings on one element. Use only one attribute
So, in order to fix this issue, we have to do something like this.
Now, check the output in the browser, it will work fine now.
So, what did we do to fix this problem? We have created an additional div with ngIf
ngFor
inside it.
This solution will work, but we created another div element. There is a way to avoid creating extra element and get the result.
So, here is the solution: ng-container
directive. Let’s see how to use it.
You can see, we have replaced <div>
with <ng-container>
directive.
As we can see, ng-container
3. ngTemplateOutlet
An embedded view from a prepared TemplateRef can be inserted ngTemplateOutlet
The template being loaded is #employeelist
ngTemplateOutlet
Summary
So, in this blog, we learn about ng-template, ng-container and ngTemplateOutlet used in any angular app. These are very powerful features of angular, and make our code more clean and dynamic. This blog basically discussed
Pingback: itemprop="name">ng-template, ng-container And ngTemplateOutlet In Angular – ZeptoBook – Angular Questions
Pingback: itemprop="name">Angular Material Table With Paging, Sorting And Filtering - ZeptoBook