Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use ng-template instead of just *ngIf

Tags:

angular

Any reason to use:

<div *ngIf="show; else notShow">content</div>
<ng-template #notShow>other content...</ng-template>

Instead of:

<div *ngIf="show">content</div>
<div *ngIf="!show">other content...</div>
like image 756
False Dragon Avatar asked Dec 24 '22 00:12

False Dragon


1 Answers

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.<div *ngIf="show">content</div>

Above will be converted to below code snippet in the DOM.

<ng-template [ngIf]="show">
  <div>content</div>
</ng-template>

Angular replaces the <ng-template> with diagnostic comments.

So if you inspect it will be like:

<!--bindings={
 "ng-reflect-ng-if":"true"
}-->
<div>content</div>

2.<ng-template *ngIf="show">content</ng-template>

This will be treated as:

<ng-template [ngIf]="show">
  <ng-template>content</ng-template>
</ng-template>

In DOM it will be

<!--bindings={
 "ng-reflect-ng-if":"true"
}-->
<!---->

For the first snippet of your code

<div *ngIf="show; else notShow">content</div>
<ng-template #notShow>other content...</ng-template>

This is how its rendered in DOM

enter image description here

For second snippet

<div *ngIf="show">content</div>
<div *ngIf="!show">other content...</div>

This is how its rendered in DOM

enter image description here


Please go through this article, it has a clear explanation for your question. ng-template

like image 89
Avinash Avatar answered Jan 09 '23 00:01

Avinash