Dynamic template reference variable inside ngFor (Angular 2)

孤人 提交于 2019-11-26 03:58:55

问题


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?


回答1:


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:

  • angular - conditional duplicate templateref in ng-content with selector



回答2:


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!



来源:https://stackoverflow.com/questions/44440879/dynamic-template-reference-variable-inside-ngfor-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!