Pass different context to ngIf

There are two very similar ways to solve this. I’ve created a stackblitz with the two solutions (tested with Angular 6.0.1 and the latest 6.1.8) for passing data to different templates based on a condition.

version #1

    <ng-container *ngTemplateOutlet="showUser ? userTmpl : emptyTmpl; context: { $implicit: user }">
    </ng-container>

    <ng-template #userTmpl let-user>
        ...
    </ng-template>

    <ng-template #emptyTmpl let-user>
        ...
    </ng-template>

version #2

Another possibility is to use @Ben’s solution, but then you have to omit the let-user part (and fix the closing tag in his code). This way the code would look like this.

    <ng-container *ngTemplateOutlet="showUser ? userTmpl : emptyTmpl; context: user">
    </ng-container>

    <ng-template #userTmpl>
        ...
    </ng-template>

    <ng-template #emptyTmpl>
        ...
    </ng-template>

Leave a Comment