【问题标题】:Create an Angular component to display a set of html table cells to embed in other tables创建一个 Angular 组件来显示一组 html 表格单元格以嵌入到其他表格中
【发布时间】:2018-08-19 19:58:15
【问题描述】:

我有很多 html 表共享相同的 15 列以及每个表特定的自定义列。我想创建这些常见的 15 列作为一个组件,它接收一组数据并显示为 15 个 td 没有包装器。我不知道如何创建一个在 DOM 中不显示包装标签并允许我传递输入的 Angular 组件。以下是我想做的事情:

<tr *ngFor="let item of items">
  <td>Column 1</td>
  <my-common-columns [data]="item"></my-common-columns>
  <td>Another column</td>
</tr>

不幸的是,在上面的代码中,&lt;my-common-columns&gt; 标签出现在渲染的 DOM 中,这弄乱了表格。我只能在tr 标签下拥有td

我也尝试了&lt;ng-container *ngComponentOutlet="myCommonColumns"&gt;,因为ng-container 没有出现在DOM 中,但我不知道如何将data 传递给它。

【问题讨论】:

    标签: html angular angular-components angular-template


    【解决方案1】:
    import { Component, TemplateRef, ViewChild } from '@angular/core';
    
    @Component({
      selector: 'my-common-columns',
      template: `<ng-template let-item>
      <td>inner item1:{{item}}</td>
      <td>inner item2:{{item}}</td>
      </ng-template>`
    })
    export class CommonComponent {
      @ViewChild(TemplateRef) template: TemplateRef<any>;
    }
    
    
    @Component({
      selector: 'my-app',
      template: `
      <table>
        <tr *ngFor="let item of data">
          <td>first</td>
          <ng-template [ngTemplateOutlet]="common.template"
                     [ngTemplateOutletContext]="{$implicit: item}">
          </ng-template>
          <td>last</td>
        </tr>
      </table>
    <my-common-columns #common></my-common-columns>
      `
    })
    export class AppComponent  {
      data = [1, 2, 3, 4, 5];
    }
    

    live example

    结果:

    ngComponentOutlet 也会在 HTML 中显示标签。 或者,您应该使用抽象来显示复杂问题的表格。

    【讨论】:

    • 哇,这真是太聪明了。我认为这确实解决了它。谢谢!我确实觉得 Angular 应该通过一种不呈现父标签的方法来让这件事变得更容易,但这就是我猜的伎俩。
    【解决方案2】:

    根据您的数据结构,您可能会执行以下操作:

    <td *ngFor="let col of item">{{ col }}</td>
    

    【讨论】:

    • 我应该说这些包含的单元格之间存在很多格式差异。在表格之间共享的一些 具有各种样式或内容,而不仅仅是简单的 {{col}}
    【解决方案3】:

    您必须将组件用作属性。 所以把它放到&lt;td my-common-column&gt;&lt;/td&gt; 并在你的组件中更改selector: [my-common-column]。这些[ ] 括号允许您将组件用作属性。

    【讨论】:

    • 但我需要一组 15 个 单元格。我只想拥有一个注入所有 15 个细胞的组件。
    • 然后将 *ngFor 放在组件上方或内部
    【解决方案4】:

    为什么不使用下面的代码?

    <tr *ngFor="let item of items">
      <td>Column 1</td>
      <td> {{ item }}</td>
      <td>Another column</td>
    </tr>
    

    【讨论】:

    • 我要包含大量 单元格。
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签