You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何借助*ngFor在Angular父组件向子组件传递自定义模板

Angular表格组件第一列自定义模板实现方案

1. 子表格组件配置

在子组件中定义输入属性接收父组件传入的模板,同时声明模板上下文类型用于传递行数据:

// table.component.ts
import { Component, Input, TemplateRef } from '@angular/core';

// 定义模板上下文,包含当前行数据
export interface TableRowContext<T> {
  $implicit: T; // 父组件可通过let-row直接获取该变量
}

@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
})
export class TableComponent<T> {
  @Input() dataSource: T[] = [];
  @Input() columnKeys: string[] = [];
  @Input() firstColumnTemplate!: TemplateRef<TableRowContext<T>>; // 接收父组件模板
}

2. 子组件模板渲染自定义列

在表格第一列位置,用ngTemplateOutlet渲染父组件传入的模板,并注入当前行的上下文数据:

<!-- table.component.html -->
<table border="1">
  <thead>
    <tr>
      <th></th>
      <th *ngFor="let key of columnKeys">{{ key }}</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let row of dataSource">
      <td>
        <!-- 渲染父组件模板,传入当前行数据 -->
        <ng-container 
          [ngTemplateOutlet]="firstColumnTemplate"
          [ngTemplateOutletContext]="{ $implicit: row }"
        ></ng-container>
      </td>
      <td *ngFor="let key of columnKeys">{{ row[key] }}</td>
    </tr>
  </tbody>
</table>

3. 父组件传入自定义模板

父组件中用ng-template编写第一列内容,通过模板变量传递给子组件,同时可通过let-row获取每行数据:

<!-- app.component.html -->
<app-table 
  [dataSource]="users"
  [columnKeys]="['name', 'age', 'email']"
  [firstColumnTemplate]="firstColTemplate"
>
</app-table>

<!-- 自定义第一列模板 -->
<ng-template #firstColTemplate let-row>
  <div>
    <span>编号: {{ row.id }}</span>
    <button (click)="viewDetail(row)">查看详情</button>
  </div>
</ng-template>

父组件数据示例:

// app.component.ts
import { Component } from '@angular/core';

interface User {
  id: number;
  name: string;
  age: number;
  email: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent {
  users: User[] = [
    { id: 1, name: '张三', age: 25, email: 'zhangsan@example.com' },
    { id: 2, name: '李四', age: 30, email: 'lisi@example.com' },
    { id: 3, name: '王五', age: 28, email: 'wangwu@example.com' },
  ];

  viewDetail(user: User) {
    console.log('用户详情:', user);
  }
}

核心说明

  • 用TemplateRef接收模板保证类型安全,避免渲染错误。
  • 通过ngTemplateOutletContext传递行数据,父组件无需额外配置即可直接使用当前行对象。
  • 若需自定义列标题,可复用相同逻辑让父组件传入标题模板,进一步提升组件灵活性。

内容的提问来源于stack exchange,提问作者techguy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 20:21:07