143

How to declare a dynamic template reference variable inside a ngFor element?

I want to use the popover component from ng-bootstrap, the popover code (with Html binding) is as shown:

<ng-template #popContent>Hello, <b>{{name}}</b>!</ng-template>
<button type="button" class="btn btn-secondary" [ngbPopover]="popContent" popoverTitle="Fancy content">
    I've got markup and bindings in my popover!
</button>

How can I wrap those elements inside ngFor?

<div *ngFor="let member of members">
    <!-- how to declare the '????' -->
    <ng-template #????>Hello, <b>{{member.name}}</b>!</ng-template>
        <button type="button" class="btn btn-secondary" [ngbPopover]="????" popoverTitle="Fancy content">
        I've got markup and bindings in my popover!
    </button>
</div>

Hmmm... any idea?

Andrew Koper
  • 6,481
  • 6
  • 42
  • 50
Boo Yan Jiong
  • 2,491
  • 5
  • 17
  • 31

3 Answers3

156

Template reference variables are scoped to the template they are defined in. A structural directive creates a nested template and, therefore, introduces a separate scope.

So you can just use one variable for your template reference

<div *ngFor="let member of members">
  <ng-template #popupContent>Hello, <b>{{member.name}}</b>!</ng-template>
  <button type="button" class="btn btn-secondary" [ngbPopover]="popupContent" popoverTitle="Fancy content">
      I've got markup and bindings in my popover!
  </button>
</div>

and it should work because it has already declared inside <ng-template ngFor

Plunker Example

For more details see also:

yurzui
  • 205,937
  • 32
  • 433
  • 399
  • 2
    Note that if you are using an `@ViewChild`, you cannot use this solution (and then should use @AlexBoisselle's one) – Random Aug 03 '20 at 11:53
39

This is the best solution I've found: https://stackoverflow.com/a/40165639/3870815

In that answer they use:

@ViewChildren('popContent') components:QueryList<CustomComponent>;

To build a list of those dynamically generated components. Highly recommend you check it out!

Alex Boisselle
  • 815
  • 9
  • 12
  • Thanks, this solved a problem I had with ng-bootstrap nav-tabs that were created in a ngFor. Having the same reference, tabs were changing simultaneously. – theomeli Dec 04 '21 at 18:22
2

Another way to allow this is to create a component that wraps the button and the ng-template

<div *ngFor="let member of members">
    <popover-button [member]="member"></pop-over-button>
</div>

And have the following in the popover-button component

<ng-template #popContent>Hello, <b>{{member.name}}</b>!</ng-template>
    <button type="button" class="btn btn-secondary" [ngbPopover]="popContent" popoverTitle="Fancy content">
    I've got markup and bindings in my popover!
</button>