ngFor(Angular 2)中的动态模板引用变量

Boo*_*ong 56 angular-template ng-bootstrap angular

如何在元素中声明动态 模板引用变量ngFor

我想使用ng-bootstrap中的popover组件,popover代码(带有Html绑定)如下所示:

<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>
Run Code Online (Sandbox Code Playgroud)

如何这些元素包装在里面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>
Run Code Online (Sandbox Code Playgroud)

嗯......任何想法?

yur*_*zui 61

模板引用变量的范围限定在它们定义的模板中.结构指令创建嵌套模板,因此引入了单独的范围.

因此,您可以使用一个变量作为模板参考

<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>
Run Code Online (Sandbox Code Playgroud)

它应该工作,因为它已经在里面声明 <ng-template ngFor

Plunker示例

有关详细信息,请参阅:

  • 请注意,如果您使用的是“@ViewChild”,则无法使用此解决方案(然后应使用@AlexBoisselle 的解决方案) (2认同)

Ale*_*lle 24

这是我找到的最佳解决方案:https : //stackoverflow.com/a/40165639/3870815

在那个答案中,他们使用:

@ViewChildren('popContent') components:QueryList<CustomComponent>;
Run Code Online (Sandbox Code Playgroud)

构建那些动态生成的组件的列表。强烈建议您检查一下!