【问题标题】:Dynamic template reference variable inside ngFor (Angular 9)ngFor(Angular 9)中的动态模板引用变量
【发布时间】:2017-11-10 11:21:31
【问题描述】:

如何在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>

我如何包装这些元素到 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>

嗯……有什么想法吗?

【问题讨论】:

  • 没有动态引用变量这样的东西。为什么你认为它需要是动态的?
  • 因为他们的教程说为了在弹出框内有 html 绑定,那么我们需要创建一个 ng-template 并使用 模板引用变量 引用它,但现在我想要在ngFor 元素中使用此弹出框
  • 照样做。即使名称相同,每个元素的模板变量也会有所不同。
  • 如果您对所有内容都使用相同的 ref 会发生什么?你测试过吗?
  • 哈,我从来没想过……我现在就测试一下……因为我一直在思考如何用“index”声明一个** 模板引用变量 "**... 待我测试后会更新... :D

标签: angular ng-bootstrap angular-template


【解决方案1】:

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

所以你可以只使用一个变量作为你的模板引用

<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>

它应该可以工作,因为它已经在 &lt;ng-template ngFor 中声明了

Plunker Example

更多详情另见:

【讨论】:

  • 请注意,如果您使用的是@ViewChild,则不能使用此解决方案(然后应使用@AlexBoisselle 的解决方案)
【解决方案2】:

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

在他们使用的答案中:

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

构建那些动态生成的组件的列表。强烈推荐你去看看!

【讨论】:

  • 最佳答案!
  • 谢谢,这解决了我在 ngFor 中创建的 ng-bootstrap nav-tabs 的问题。具有相同的引用,标签同时改变。
【解决方案3】:

你可以在*ngFor中使用trackBy: trackByFn

<div *ngFor="let member of members;trackBy: trackByF">
    <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>

【讨论】:

    【解决方案4】:

    另一种方法是创建一个包装按钮和 ng-template 的组件

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

    并且在 popover-button 组件中有以下内容

    <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>
    

    【讨论】:

      猜你喜欢
      • 2020-08-27
      • 2020-04-17
      • 1970-01-01
      • 2018-07-14
      • 2017-04-27
      • 2018-06-24
      • 2017-11-18
      • 1970-01-01
      相关资源
      最近更新 更多