Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do i really use ng-template in angular 2+

I am wondering what is the ideal situation for using ng-template. I have below scenario. Code was like below

<div *ngIf="somecond">html inside1</div>
<div *ngIf="somecond1">html inside2</div>
<div *ngIf="somecond2">html inside3</div>

Other developer modified like below

<ng-template #text1>html inside1</ng-template>
<ng-template #text2>html inside2</ng-template>
<ng-template #text3>html inside3</ng-template>

<div *ngIf="somecond;then text1"></div>
<div *ngIf="somecond1;then text2"></div>
<div *ngIf="somecond2;then text3"></div>

Is above the right way of using ng-template or normal code is better in this scenario. When do i really use ng-template

like image 357
Hacker Avatar asked Jan 28 '23 22:01

Hacker


1 Answers

The ideal situation for ng-template is when you want to use the else statement.

Instead of:

<div *ngIf="isDisplayed">Item 1</div>
<div *ngIf="!isDisplayed">Item 2</div>

You can do this:

<div *ngIf="isDisplayed; else showItem2">Item 1</div>

<ng-template #showItem2>
Item 2
</ng-template>
like image 53
TheUnreal Avatar answered Feb 05 '23 17:02

TheUnreal