How to declare dynamic template reference variable inside ngFor with Angular?

Sometimes, we want to declare dynamic template reference variable inside ngFor with Angular.

In this article, we’ll look at how to declare dynamic template reference variable inside ngFor with Angular.

How to declare dynamic template reference variable inside ngFor with Angular?

To declare dynamic template reference variable inside ngFor with Angular, we can declare one variable.

For instance, we write

<div *ngFor="let member of members">
  <ng-template #popupContent>
    <b>{{ member.name }}</b>
  </ng-template>
  <button
    type="button"
    class="btn btn-secondary"
    [ngbPopover]="popupContent"
    popoverTitle="Fancy content"
  >
    ...
  </button>
</div>

to define the popupContent in the *ngFor loop.

Then we can access all the items with the popupContent ref name from ViewChildren with

export class Component implements OnInit, AfterViewInit {
  //...
  @ViewChildren("popupContent") components: QueryList<CustomComponent>;
  //...
}

in the iterable query list.

Conclusion

To declare dynamic template reference variable inside ngFor with Angular, we can declare one variable.