How to pass context to Angular 5 template from *ngIf

BeetleJuice picture BeetleJuice · Feb 15, 2018 · Viewed 8.3k times · Source

Angular's NgTemplateOutlet allows you to pass a context to the outlet for property binding.

<ng-container *ngTemplateOutlet="eng; context: {$implicit: 'World'}"></ng-container>
<ng-template #eng let-name><span>Hello {{name}}!</span></ng-template>

Angular's *ngIf allows you to embed one template or another based on a boolean condition:

<ng-container *ngIf="isConditionTrue; then one else two"></ng-container>
<ng-template #one>This shows when condition is true</ng-template>
<ng-template #two>This shows when condition is false</ng-template>

How can I pass context to these templates referred to within the *ngIf syntax?

Answer

Sielu picture Sielu · Jun 21, 2018

Actually you can input your condition into ngTemplateOutlet (and get rid of ngIf).

<ng-container *ngTemplateOutlet="condition ? template1 : template2; context: {$implicit: 'World'}">
</ng-container>