Hacker
Hacker

Reputation: 7906

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

Upvotes: 5

Views: 6090

Answers (2)

Nima Hakimi
Nima Hakimi

Reputation: 1392

ng-template has a couple of (not so common) use cases. Its content is not shown and you can use angular dom local variables to send it to a directive or component's input so they show it as they wish.

*ngIf, *ngFor or *ngSwitch use it under the hood actually and the asterisk version is just an alias.

As @TheUnreal said one of its main use cases is else statement like showing a loading:

<ng-template #loading>loading...</ng-template>
<div *ngIf="data; else loading">
   Content
</div>

Your example though is probably not the ideal way to use it as it's just causing complication in your template.

Upvotes: 1

TheUnreal
TheUnreal

Reputation: 24472

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>

Upvotes: 9

Related Questions