【问题标题】:Passing ng-template to child component将 ng-template 传递给子组件
【发布时间】:2020-04-22 07:29:39
【问题描述】:

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

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

<!-- 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' }
];

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

<!-- 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'];
}

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

<ng-template #quizScore>
  {{ someReferenceToData | percent }} // This treatment gets passed to child
</ng-template>

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

【问题讨论】:

    标签: angular angular-components angular-template


    【解决方案1】:

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

    但是,我建议通过为您的列配置创建一个接口进行一些重构,该接口具有header、key 和可选的customCellTemplate。比如:

    重构

    import { TemplateRef } from '@angular/core';
    
    export interface TableColumnConfig {
      header: string;
      key: string;
      customCellTemplate?: TemplateRef<any>;
    }
    

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

    // CHILD COMPONENT
    @Input() columnConfigs: TableColumnConfig[];
    @Input() rows: any[];
    

    在父组件中

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

    HTML

    <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>
    

    TS - 在 ngOnInit / 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'}
      ]
    }
    

    注意 static:true 与 static:false - 模板引用是静态的,除非它使用 *ngIf 或 *ngFor 等动态呈现。 static:true 将在ngOnInit 中初始化模板引用,static: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>
    

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

    【讨论】:

    • 这非常有效,除非我在模板中的数据上使用管道传递给子组件。当我执行{{ someReferenceToData | percent }} 时,没有渲染任何内容,但控制台中没有错误。我可以单步调试调试器,看看我是否可以从这里弄清楚发生了什么,但我想我会提到它。
    • 不确定您是否使用了render() 函数,但这可能与此有关?不能肯定地说。我倾向于尽可能避免模板中的功能。我在使用row[col.key] 时没有遇到问题。
    • 这绝对不是渲染功能,因为它已被删除。一旦我弄清楚了,我会发表后续评论,以防其他人遇到同样的问题。
    • FWIW,我可以通过将传递给子组件的模板更改为 &lt;ng-template #customCellTemplate *ngTemplateOutlet="col.customCellTemplate; context: { $implicit: render(col.key, row) }"&gt;&lt;/ng-template&gt; 来完成这项工作
    • 很抱歉在一整年后添加另一条评论,最近的一条通知让我重新阅读了我的答案,我在 sn-p 中发现了一个小错字,在那里我有 let-someReferenceData (missing ' To') 在模板中,但 someReferenceToData 在插值中。将 sn-p 更新为 let-someReferenceToData。这可以解释您看到的问题。
    【解决方案2】:

    也许您可以在子组件中创建一个事件监听器,并在使用 RxJS 发出格式化数据时呈现正确的数据。

    【讨论】:

      【解决方案3】:

      我的建议是像这样定义一个column 对象:

      export class Column {
        header: string;
        key: string;
        type: ColumnType; // An enumerator: plain text, number, percentage, date
      }
      
      

      在您的子组件中,您可能拥有处理不同类型列的显示逻辑的管道或其他函数

      render(type: ColumnType, row: any) {
        switch(type) {
          case ColumnType.Date: 
            // format as date
            break;  
          case ColumnType.Number: 
            // Format number to 2 decimals for example
            break;  
        }
      }
      

      【讨论】:

      • 我们在之前的组件迭代中尝试过这个。它确实有效,但我们最终使用了一个巨大的 switch 语句来处理一次性事件,因为 date 有时会是 shortDate,而其他时候会是 longDate 等等。这一次我们正在寻找更大的灵活性。
      猜你喜欢
      • 2018-09-02
      • 2018-08-03
      • 2020-05-07
      • 2018-08-05
      • 1970-01-01
      • 2018-11-30
      • 2019-10-04
      • 1970-01-01
      • 2021-09-25
      相关资源
      最近更新 更多