Know about <ng-template> and its Usage
I have almost one year of experience in web development. I have worked on React for 10 months and just moved to angular.
Recently I was working on an Angular 4 project where I had to render a table based on some conditions. I came across *ngIf
and <ng-template>
. Here I will show the usage of the ng-template
with the example. So bare with me, till the end, you will have a complete idea of how it works.
ng-template
is the template element which appears on DOM when some condition is true. This condition is described by the structural directives for example *ngIf
, *ngFor
, etc. Structural directives remove or add elements from the DOM. Instead of hiding an element, they completely remove it from the DOM.
Consider an example where we will show a text (‘Div one’) when a flag is true. The ‘flag’ gets true when we click on a button which will change the state of the ‘flag’ to true. So, here we will simply use the *ngIf
.
How to use <ng-template>?
You will be amazed to know how this actually works. The *ngIf
directive actually moves into the <ng-template>
as property binding [ngIf]
and rest of the elements move inside of the <ng-template>
element including the <div>
as shown below.
What if we want to show another template when the condition is different?
One way to do that is to define another div and add the if condition again but here we will render the different template using if else condition as shown below.
Here we have defined the template reference variable #div1 and #div2. The first template triggers when the flag condition gets true and second triggers when the flag gets false.
❤️ Like, Share or Leave A Comment!
If you enjoyed this post, don’t forget to give it a 👏🏼, share it with a friend you think might benefit from it and leave a comment! Stay tuned for more exciting blogs on Flutter, Elixir, React, Angular, Ruby, etc.
Thanks !!