1

Here is what I am trying to accomplish. I have a table element on my HTML page. The table has a complicated row structure. Every three rows are related to a single data item. Right now, the table is hard-coded HTML and very complex/messy looking, so I'd like to make a component instead, which will replace many tr elements and also allow me to use *ngIf a little more cleanly.

So, just to be clear, instead of this (the existing HTML, I removed all the td, tbody and other tags for simplicity sake):

<table>
  <tr>Item1</tr>
  <tr>Item1</tr>
  <tr>Item1</tr>
  <tr>Item2</tr>
  <tr>Item2</tr>
  <tr>Item2</tr>
  <tr>Item3</tr>
  <tr>Item3</tr>
  <tr>Item3</tr>
</table>

I want to use this:

<table>
  <app-row item="item1"></app-row>
  <app-row item="item2"></app-row>
  <app-row item="item3"></app-row>
</table>

or something like this:

<table>
  <app-row *ngFor="let item of items"></app-row>
</table>

SO HERE IS THE PROBLEM

When I try to do this using a component, what I end up with is this. It has the component tag wrapped around each section of tr elements. This is not only improper HTML, but it breaks CSS selectors which expect a table to look like table>tr>td.

<table>
  <app-row>
    <tr>Item1</tr>
    <tr>Item1</tr>
    <tr>Item1</tr>
  </app-row>
  <app-row>
    <tr>Item2</tr>
    <tr>Item2</tr>
    <tr>Item2</tr>
  </app-row>
  <app-row>
    <tr>Item3</tr>
    <tr>Item3</tr>
    <tr>Item3</tr>
  </app-row>
</table>

I did a little research and everyone seems to recommend using an "attribute selector" instead, which might look like this:

<table>
  <tr appRow item="item1"></tr>
  <tr appRow item="item2"></tr>
  <tr appRow item="item3"></tr>
</table>

However that results in having double tr tags in all cases.

<table>
    <tr>
        <tr>Item1</tr>
        <tr>Item1</tr>
        <tr>Item1</tr>
    </tr>
      <tr>
        <tr>Item2</tr>
        <tr>Item2</tr>
        <tr>Item2</tr>
      </tr>
      <tr>
        <tr>Item3</tr>
        <tr>Item3</tr>
        <tr>Item3</tr>
      </tr>
</table>

Can anyone recommend a way to create this structure so that I have the correct resulting HTML without additional tags?

1
  • 1
    The only thing that comes to my mind are templates. Check out this example I created, maybe it can give you some ideas... Commented Oct 28, 2019 at 21:39

1 Answer 1

2

using the attribute selector is also a solution , but you have to apply the attribute to the <table> and leave you component generate the <tr>s.

<table appRow *ngFor="let item of items" [itemInput]="item">
</table>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.