我正在寻找将当前组件范围数据传递到 ng-content
指令的解决方案。
我有 app-table
组件模板,其中包含我想传递给子内容的数据,使用如下解决方案:
<!-- some html before -->
<table>
<!-- complex header markup with sorting/filtering support -->
<tr *ngFor="let item of data">
<ng-content [value]="item"></ng-content> //how to pass data?
</tr>
</table>
//some html after
以及我想使用这些数据的页面模板:
<app-table>
<td>{{value.Name}}</td>
...
</app-table>
这可能吗?
最佳答案
我遇到了同样的问题,为了更加清楚,我添加了您的示例。
<!-- some html before -->
<table>
<!-- complex header markup with sorting/filtering support -->
<tr *ngFor="let item of data">
<ng-template [ngTemplateOutlet]="templateRef" [ngTemplateOutletContext]="{$implicit: item}"></ng-template>
</tr>
</table>
//some html after
在组件中,你需要这样声明templateRef
。
export class AppTableComponent {
...
@ContentChild(TemplateRef) templateRef: TemplateRef<any>;
...
}
然后像这样使用你的组件。
<app-table>
<ng-template let-item>
<td>{{item.Name}}</td>
...
</ng-template>
</app-table>
关于angular - 将范围数据传递到 Angular2 中的 ng-content,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41510470/