ngIf not working with ng-template

Viewed 6061

I want to show or hide a template based on the boolean value in Angular 4. Below are the HTML and code

--- This is inside Home.Component.HTML

<ng-template [ngIf]="isSummaryViewVisbile" #pricebookView ></ng-template>

---- This is inside HomeComponent

   isSummaryViewVisbile: boolean = true;

Above code doesn't work, it always hides template although I'm assigning true.

Thanks in advance.

2 Answers

The ng-template is an Angular element for rendering HTML. It is never displayed directly. In fact, before rendering the view, Angular replaces the and its contents with a comment.If there is no structural directive and you merely wrap some elements in a ng-template, those elements disappear.

<p>Hip!</p>
<ng-template>
  <p>Hip!</p> //would disappear
</ng-template>
<p>Hooray!</p>

So the following code would work fine

isSummaryViewVisbile = true;

<ng-template [ngIf]="isSummaryViewVisbile" #pricebookView >
       Hello world.
</ng-template>

But if you replace [ngIf] with *ngIf, same code would not work.

Because Internally, Angular translates the *ngIf attribute into a ng-template element, wrapped around the host element. For example

<ng-template *ngIf="isSummaryViewVisbile" #pricebookView >
       Hello world.
</ng-template>

Would be converted to-

<ng-template [ngIf]="isSummaryViewVisbile">
      <ng-template #pricebookView >
           Hello world.
    </ng-template>
</ng-template>

Now as we can see inner ng-template will always hide it's content.I hope this makes clear.

Demo: https://plnkr.co/edit/yB7PKx?p=preview

As per Mohit's answer/comment your code is valid... if you were to assign content to the ng-template tag it should show.

Related