Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass data to template parameter via *ngIf?

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading