Jeremy
Jeremy

Reputation: 1073

Create an Angular component to display a set of html table cells to embed in other tables

I have a lot of html tables that share the same 15 columns along with custom columns that are specific for each table. I would like to create these common 15 columns as a component that takes in a set of data and shows up as the 15 td's without a wrapper. I can't figure out how to create an Angular component that doesn't show the wrapper tag in the DOM and allows me to pass in input. Below is kind of what I'd like to do:

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

Unfortunately with the above code, <my-common-columns> tag shows up in the rendered DOM, which messes up the table. I can only have td's under the tr tag.

I also tried <ng-container *ngComponentOutlet="myCommonColumns"> since ng-container's don't show up in the DOM, but I can't figure out how to pass data into it.

Upvotes: 7

Views: 3702

Answers (4)

DiPix
DiPix

Reputation: 6083

You have to use your component as a attribute. So put it to <td my-common-column></td> and in your component change selector: [my-common-column]. These [ ] brackets allows you to use component as attribute.

Upvotes: 0

Ilia Volk
Ilia Volk

Reputation: 556

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

result:

result

ngComponentOutlet will show tag in HTML too. Either, you should use abstraction to display tables for complex problems.

Upvotes: 5

Johan Swanepoel
Johan Swanepoel

Reputation: 482

Depending on your data structure you could probably do something like:

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

Upvotes: 1

Alex Seitz
Alex Seitz

Reputation: 109

Why don't you use the code below?

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

Upvotes: -1

Related Questions