Angular 2将已包含的内容绑定到循环变量 [英] Angular 2 bind transcluded content to loop variable

查看:124
本文介绍了Angular 2将已包含的内容绑定到循环变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将已包含的内容绑定到组件循环内的变量,但无法这样做.

I'm trying to bind transcluded content to a variable inside of a component loop but I'm unable to do so.

我看过PrimeNG的dropdown组件,它们使用template标记和let-car绑定到循环的car变量.

I've looked at the PrimeNG's dropdowncomponent and they use the template tag along with let-car to bind to the car variable of the loop.

但是,当我尝试此操作时,我什至无法获得内容的内容.实现这一目标的正确方法是什么?

However when I try this I can't even get the content to transclude. What is the correct way of achieving this?

尝试:

<!-- Obviously not gonna work -->
<comp>
  <span>{{option.name}}, {{option.type}}</span>
</comp>

<!-- Thought this would work but it doesn't, in odd scenarios I get the last element of the loop to transclude content and bind correctly. -->
<comp>
  <template let-option>
    <span>{{option.name}}, {{option.type}}</span>
  </template>
</comp>

在组件中:

<ul>
  <li *ngFor="let option of options">
    <ng-content></ng-content>
  </li>
</ul>

我想要达到的目标的简单方法:

Simple plunkr of what I'm trying to achieve:

https://plnkr.co/edit/6SS03fuXmbvJB4nmf1AO?p=preview

推荐答案

更新Angular 6

ngOutletContext重命名为ngTemplateOutletContext template应该是ng-template

另请参见 https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

原始

您可以获取模板引用,并使用例如ngTemplateOutletngForTemplate将其添加以将模板内容添加到DOM中.使用ngTemplateOutlet,您可以提供自己的上下文,然后可以在尝试时使用模板变量进行访问.

You can get the template reference and add it using for example ngTemplateOutlet or ngForTemplate to get the template content added to the DOM. With ngTemplateOutlet you can provide your own context that you then can access with template variables as you tried.

class CompComponent {
  context = {option: 'some option'};
  constructor(private templateRef:TemplateRef){}
}

<ng-template [ngTemplateOutlet]="templateRef" [ngOutletContext]="{$implicit: context}"></ng-template>

我认为在较新版本中,这应该是

<ng-template [ngTemplateOutlet]="templateRef" [ngTemplateOutletContext]="{$implicit: context}"></ng-template>

(但尚未验证)

另请参见

  • How to repeat a piece of HTML multiple times without ngFor and without another @Component
  • Angular2 child component as data

这篇关于Angular 2将已包含的内容绑定到循环变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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