Pass different context to ngIf

Viewed 20590

Take the following template example. The Im creating a template context of user with the as syntax and would like to pass that context into the userTmpl. From what I can tell there's no way to pass context outside of what is used by the ngIf condition. Which in this example, is the showUser property.

<ng-container *ngIf="user$ | async as user">
    <ng-container *ngIf="showUser; then userTmpl; else emptyTmpl"></ngcontainer>
</ng-container>

How can you pass the user template input variable to the nested templateRef?

Looking at the source, the ngIf directive looks like it sets the context to the condition of the ngIf. Im not aware of a way to basically override that context variable thats used within the templates

Something like this would be ideal, but not seeing a way to do it.

<ng-container *ngIf="showUser; then userTmpl; else emptyTmpl; context: user"></ngcontainer>
4 Answers

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>

You can achieve that this way :

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