Home > Back-end >  How to pass data to template parameter via *ngIf?
How to pass data to template parameter via *ngIf?

Time:08-28

Can we pass [1,2,3] to parameter p of template A and pass [4,5,6] to parameter q of template B from *ngIf?

<div *ngIf="true;then A;else B"></div>

<ng-template #A let-p>p: {{p}}</ng-template>
<ng-template #B let-q>q: {{q}}</ng-template>

Here is my attempt but it does not work.

<div *ngIf="true;then A; context:{$implicit:[1,2,3]};else B;context:{$implicit:[4,5,6]}"></div>

<ng-template #A let-p>p: {{p}}</ng-template>
<ng-template #B let-q>q: {{q}}</ng-template>

CodePudding user response:

I think with single ternary operator is difficult to work for your requirement.

Approach 1: With [ngSwitch] [ngTemplateOutlet]

<div [ngSwitch]="true">
  <ng-container
    *ngSwitchCase="true"
    [ngTemplateOutlet]="A"
    [ngTemplateOutletContext]="{ $implicit: [1, 2, 3] }"
  >
  </ng-container>

  <ng-container
    *ngSwitchDefault
    [ngTemplateOutlet]="B"
    [ngTemplateOutletContext]="{ $implicit: [4, 5, 6] }"
  >
  </ng-container>
</div>

Approach 2: With [ngTemplateOutlet] and multiple ternary operators

<div>
  <ng-container
    [ngTemplateOutlet]="true ? A : B"
    [ngTemplateOutletContext]="{ $implicit: true ? [1, 2, 3] : [4, 5, 6] }"
  >
  </ng-container>
</div>

Demo Apprach 1 & 2 @ StackBlitz

  • Related