55

I have a condition in the template as follows:

<ng-container>
    <p *ngFor="let seat of InfoDetails?.seatInfo">
        <template *ngIf="seat.section">
            Section {{seat?.section}} ,
        </template>
        <template *ngIf="seat.row">
            Row {{seat?.row}},
        </template>
        <template *ngIf="seat.seatNo">
            Seat number {{seat?.seatNo}}
        </template>
    </p>
</ng-container>

I have dataset that contains row and seatNo, but it does not seem to print in the template. what is the issue here?

Lazar Ljubenović
  • 15,745
  • 7
  • 45
  • 80

1 Answers1

108

Read the doc here https://angular.io/guide/structural-directives especially for

<div *ngIf="hero" >{{hero.name}}</div>

The asterisk is "syntactic sugar" for something a bit more complicated. Internally, Angular desugars it in two stages. First, it translates the *ngIf="..." into a template attribute, template="ngIf ...", like this.

<div template="ngIf hero">{{hero.name}}</div>

Then it translates the template attribute into a element, wrapped around the host element, like this.

<ng-template [ngIf]="hero"> <div>{{hero.name}}</div></ng-template>

  • The *ngIf directive moved to the element where it became a property binding,[ngIf].
  • The rest of the , including its class attribute, moved inside the element.

So for it we have ng-container

 <ng-container *ngIf="seat.section">
    Section {{seat.section}} ,
 </ng-container>

or use span or div or regular html tag.

 <span *ngIf="seat.section">
    Section {{seat.section}} ,
 </span>

or if you still want to use ng-template (not recommended)

<ng-template [ngIf]="seat.section">
  Section {{seat.section}} ,
</ng-template>
jonrsharpe
  • 99,167
  • 19
  • 183
  • 334
Fetrarij
  • 6,506
  • 3
  • 24
  • 32
  • 'ng-template' is not a known element: –  Jun 30 '17 at 05:03
  • answer by @Fetra R. is a way to go for this question-

    Section {{seat?.section}} , Row {{seat?.row}}, Seat number {{seat?.seatNo}}

    – Rahul Singh Jun 30 '17 at 05:19
  • If ng-template is not recognized use template, you may use an older version than angular4.0.0-rc.1 https://github.com/angular/angular/blob/master/CHANGELOG.md – Fetrarij Jun 30 '17 at 05:28
  • 2
    Someone here: https://stackoverflow.com/questions/47478041/using-ng-template-for-ngif#47478041 wants to know why you say it's not recommended to use the ng-template. – Gilles Nov 24 '17 at 17:50