【问题标题】:Angular 2 bind transcluded content to loop variableAngular 2 将嵌入的内容绑定到循环变量
【发布时间】:2017-05-05 12:24:06
【问题描述】:

我正在尝试将嵌入的内容绑定到组件循环内的变量,但我无法这样做。

我查看了 PrimeNG 的 dropdowncomponent,他们使用 template 标签和 let-car 绑定到循环的 car 变量。

但是,当我尝试这个时,我什至无法让内容嵌入。实现这一目标的正确方法是什么?

尝试:

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

我想要实现的简单plunkr:

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

【问题讨论】:

  • 在 cmets 中找到了一个完整的例子

标签: angular typescript


【解决方案1】:

更新 Angular 6

ngOutletContext 更名为ngTemplateOutletContext template 应该是 ng-template

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

原创

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

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>

(但尚未验证)

另见

【讨论】:

  • context 到底应该是什么?
  • 对于那个 templateRef 来说可能是类似“this”的东西。我只是在猜测(:我自己也在研究这种模式。
  • @GünterZöchbauer 如果您有时间,您能否更详细地解释一下 templateRef(和 let-something 属性)是如何工作的?文档很糟糕(;
  • plnkr.co/edit/JuwbvVe5sBGMI9Xm2DsS?p=preview 如果传递给ngOutletContext 的对象具有$implicit 属性,则只需let-xxx 即可使其可用,然后xxx 获取$implicit 属性的值。
  • 不知道如何,但经过数小时的努力,您的回复对我有所帮助,非常感谢!
猜你喜欢
  • 2016-09-16
  • 2019-11-30
  • 2019-03-26
  • 2018-09-03
  • 2018-09-22
  • 2016-12-28
  • 2021-10-13
  • 1970-01-01
  • 2017-01-12
相关资源
最近更新 更多