ngFor 中的动态模板引用变量(Angular 9) [英] Dynamic template reference variable inside ngFor (Angular 9)

查看:102
本文介绍了ngFor 中的动态模板引用变量(Angular 9)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

你好,{{name}}!<按钮类型=按钮"class =btn btn-secondary"[ngbPopover]=popContent"popoverTitle=花哨的内容">我的弹出窗口中有标记和绑定!

如何将这些元素包装ngFor 中?

<!-- 如何声明 '????'--><ng-template #????>你好,<b>{{member.name}}</b>!</ng-template><按钮类型=按钮"class =btn btn-secondary"[ngbPopover]=????"popoverTitle=花哨的内容">我的弹出窗口中有标记和绑定!

嗯……有什么想法吗?

解决方案

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

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

<ng-template #popupContent>你好,<b>{{member.name}}</b>!</ng-template><button type="button" class="btn btn-secondary" [ngbPopover]="popupContent" popoverTitle="花式内容">我的弹出窗口中有标记和绑定!

它应该可以工作,因为它已经在 <ng-template ngFor

中声明

Plunker 示例

有关更多详细信息,另请参阅:

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?

解决方案

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:

这篇关于ngFor 中的动态模板引用变量(Angular 9)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆