angular - 将范围数据传递到 Angular2 中的 ng-content

标签 angular typescript

我正在寻找将当前组件范围数据传递到 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/

相关文章:

angular - ng-bootstrap 示例从组件调用方法

Angular自定义异步验证器保持待处理状态

javascript - 使用 Typescript 在 Angular2 中导出对象文字

javascript - 未能 "dynamically"导入 date-fns/locale 库 - TypeScript 给出尝试导入错误

reactjs - 将react-hook-form与@mui/x-date-pickers v6一起使用

javascript - 如何动态更改下拉选项

html - HTML 中的属性和特性有什么区别?

javascript - 错误 下拉列表验证错误 : mat-form-field must contain a MatFormFieldControl.

angular - 如何为 *ngFor angular 中的项目创建不同的模板引用变量

javascript - 调整 XHR header