In this blog, we are going to explore the most important features of angular. We will explore
Let’s explore each feature one by one.
<ng-template> is used to render
Let’s create our first
ng-template like this showing below:
So the complete code will be like:
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
What is <ng-template> in Angular?
<ng-template>is a virtual element and its contents are displayed only when used along with structural directives
.That’s why our template doesn’t show up in aboveexample.
<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
Using <ng-template> with [ngIf] directive
To display our template, simply we will
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
In the above code, we have created
Let’s see the case, where we can
Here in the above code, we have
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
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
As we can see,
An embedded view from a prepared TemplateRef can be inserted
The template being loaded is
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