将 ng-template 传递给子组件

Hug*_*hes 6 angular-template angular-components angular

我创建了一个可重用的组件来呈现表格。它目前适用于基本表格,但在某些情况下我希望能够自定义表格中的单个列/单元格。

这是我在父组件中使用的代码:

<!-- PARENT TEMPLATE -->
<app-table
  [headers]="headers"
  [keys]="keys"
  [rows]="rows">
</app-table>

// PARENT COMPONENT
public headers: string[] = ['First', 'Last', 'Score', 'Date'];
public keys: string[] = ['firstName', 'lastName', 'quizScore', 'quizDate'];
public rows: Quiz[] = [
  { 'John', 'Doe', 0.75, '2020-01-03T18:18:34.549Z' },
  { 'Jane', 'Doe', 0.85, '2020-01-03T18:19:14.893Z' }
];
Run Code Online (Sandbox Code Playgroud)

我在子组件中使用的代码:

<!-- CHILD TEMPLATE -->
<table>
  <thead>
    <tr>
      <td *ngFor="let header of headers">
        {{ header }}
      </td>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let row of rows">
      <td *ngFor="let key of keys">
        {{ render(key, row) }}
      </td>
    </tr>
  </tbody>
</table>

// CHILD COMPONENT
@Input() headers: string[];
@Input() keys: string[];
@Input() rows: any[];

render(key: string, row: any) {
  return row['key'];
}
Run Code Online (Sandbox Code Playgroud)

我希望能够在父组件中声明一个模板来修改子组件中的数据。例如,将测验分数转换为百分比或格式化日期,而不直接更改组件中的数据。我设想类似以下内容:

<ng-template #quizScore>
  {{ someReferenceToData | percent }} // This treatment gets passed to child
</ng-template>
Run Code Online (Sandbox Code Playgroud)

通过将其传递到我的子组件中,它将获取我渲染的数据并使用百分比管道对其进行格式化。我已经对ngTemplateOutletngComponentOutletng-content等进行了一些研究,但不确定最好的方法。

Chr*_*man 7

您需要将TemplateRefs 从父组件传递到子(表)组件。根据您当前的方法,一种方法是@ViewChild为父组件中的引用创建另一个数组,并将其传递给表组件。

但是,我建议通过为您的列配置创建一个接口进行一些重构,该接口具有headerkey和可选的customCellTemplate. 就像是:

重构

import { TemplateRef } from '@angular/core';

export interface TableColumnConfig {
  header: string;
  key: string;
  customCellTemplate?: TemplateRef<any>;
}
Run Code Online (Sandbox Code Playgroud)

然后您可以简化子组件的输入

// CHILD COMPONENT
@Input() columnConfigs: TableColumnConfig[];
@Input() rows: any[];
Run Code Online (Sandbox Code Playgroud)

在父组件中

您对父级中自定义单元格模板定义的愿景是正确的,但您需要访问数据。

超文本标记语言

<app-table
  [columnConfigs]="columnConfigs"
  [rows]="rows">
</app-table>

<!-- name the $implicit variable 'let-whateverIwant', see below for where we set $implicit -->
<!-- double check variable spelling with what you are trying to interpolate -->
<ng-template #quizScore let-someReferenceToData>
  {{ someReferenceToData | percent }} // The parent component can do what it likes to the data and even styles of this cell.
</ng-template>
Run Code Online (Sandbox Code Playgroud)

ngOnInitTS - 模板引用在/ngAfterViewInit生命周期挂钩之前未定义

// PARENT COMPONENT
@ViewChild('quizScore', { static: true }) customQuizTemplate: TemplateRef<any>;

public columnConfigs: TableColumnConfiguration[];
public rows: Quiz[] = [
  { 'John', 'Doe', 0.75, '2020-01-03T18:18:34.549Z' },
  { 'Jane', 'Doe', 0.85, '2020-01-03T18:19:14.893Z' }
];

ngOnInit() {
  this.columnConfigs = [
    {key: 'firstName', header: 'First'},
    {key: 'lastName', header: 'Last'},
    {key: 'quizScore', header: 'Score', customCellTemplate: customQuizTemplate},
    {key: 'quizDate', header: 'Date'}
  ]
}
Run Code Online (Sandbox Code Playgroud)

关于static:truevs 的static:false注意事项- 模板引用是静态的,除非它是用*ngIf或 之类的东西动态渲染的*ngForstatic:true将在 中初始化模板引用ngOnInitstatic:false将在 中初始化它ngAfterViewInit

在子组件中

您已经在表中放置了嵌套的 *ngFor,但如果有 customCellTemplate,则需要进行一些内容投影。

<tr *ngFor="let row of rows">
  <td *ngFor="let col of columnConfigs">
    <!-- if there is no customCellTemplate, just render the data -->
    <div *ngIf="!col.customCellTemplate; else customCellTemplate">
        {{ render(col.key, row) }}
    </div>

    <ng-template #customCellTemplate>
      <!-- expose data, you could expose entire row if you wanted. but for now this only exposes the cell data -->
      <ng-template [ngTemplateOutlet]="col.customCellTemplate"
        [ngTemplateOutletContext]="{ $implicit: {{ render(col.key, row) }} }">
      </ng-template>
    </ng-template>  
  </td>
</tr>
Run Code Online (Sandbox Code Playgroud)

旁注:如果可以的话,我会替换render(col.key, row)为。row[col.key]