【问题标题】:(Angular 2+) Using ng-content in *ngFor, cannot access the loop variables(Angular 2+)在 *ngFor 中使用 ng-content,无法访问循环变量
【发布时间】:2017-07-02 01:29:45
【问题描述】:

如何转换/投影到循环内的插槽中,并使投影的内容能够访问循环变量?

假设我有一个包含以下内容的基本组件

<tr *ngFor="let data of items">
    <td>{{data.title}}</td>
    <ng-content select="[slot]"></ng-content>
</tr>

还有一个子组件,使用了transclusion slot "slot"

<parent [items]="items"> 
    <ng-container slot>
        <td>{{data.category}}</td>
        <td>{{data.number}}</td>
    </ng-container>
</parent>

我想要生成的 HTML 是

<tr>
    <td>{{data.title}}</td>
    <td>{{data.category}}</td>
    <td>{{data.number}}</td>
</tr>

但实际发生的是子组件中没有定义“数据”,这是有道理的。有什么办法可以让它像这样工作吗?

【问题讨论】:

  • 你在哪里调用子组件
  • @developer033 我在另一个组件中调用子组件。所以&lt;child-component&gt;&lt;/child-component&gt; 子组件通过 xhr 抓取进入项目的数据并将其传递给父组件,如下所示: {{data.category }} {{data.number}}
  • 完全正确。我正在尝试获取“数据”-循环变量到子组件中,就像你通常在树枝中一样
  • 听起来你想要这个:toddmotto.com/…
  • @RudolfOlah 我看过那个教程。我正在使用多槽嵌入/投影,但这里的问题是我使用的是循环中的槽。

标签: javascript angular ngfor ng-template


【解决方案1】:

使用TemplateRef 可以在模板级别以声明方式声明在两个组件之间起作用的模板变量。以下解决方案与您的“插槽”基础架构不完全匹配,但可能有助于进一步调查。

list.component.ts

import { Component, Input, ContentChild, TemplateRef } from '@angular/core';

@Component({
  selector: 'list',
  template: `
    <tr class="box" *ngFor="let data of items">
      <td>{{data.title}}</td>
      <ng-template
        [ngTemplateOutlet]="template"
        [ngTemplateOutletContext]="{ $implicit: data }">
      </ng-template>
    </tr>`
})
export class ListComponent {
  @Input() items;
  @ContentChild(TemplateRef) template: TemplateRef;
  constructor() { }
}

wrapper.component.ts

import { Component, ContentChild, TemplateRef } from '@angular/core';

@Component({
  selector: 'wrapper',
  template: `
    <table>
      <list [items]="items">
        <ng-template let-data>
          <td>{{data.category}}</td>
          <td>{{data.number}}</td>
        </ng-template>
      </list>
    </table>`
})
export class WrapperComponent {
  items = [
    { title: 'T1', category: 'C1', number: 'N1' },
    { title: 'T2', category: 'C2', number: 'N2' },
    { title: 'T3', category: 'C3', number: 'N3' }
  ];
  @ContentChild(TemplateRef) template: TemplateRef;
  constructor() { }
}

我还创建了一个Plunker demo...

【讨论】:

    猜你喜欢
    • 2017-03-04
    • 2018-04-09
    • 2018-03-30
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 2018-02-27
    相关资源
    最近更新 更多