htmlmysqlangularfor-loopangular-components

How do I make a child component not render the extra <app-child> node?


I have a parent component whose template is basically this:

<table>
  <thead>
    <tr>
      <th>Data 1</th>
      <th>Data 2</th>
    </tr>
  </thead>
  <tbody>
    @for(item of items; track item.id) {
    <child [item]="item" (event1)="eventFunc.emit()"></child>
    }
  </tbody>
</table>

And a child component whose template is:

<tr>
  <td>
    {{item().id}}
  </td>
  <td>
    {{item().name}}
  </td>
</tr>

When rendered, an extra wrapper node is added around the child component, which is causing the table to fall apart as it's not getting what was expected.

I tried looking up online and the first solution that was given was use of ngContainer, which doesn't seem to work, or I am doing it wrong.

I need to the child component to be separate because in my code there are actually 6 rows and multiple child-specific events, which would be a mess if written all in the parent component. Child components individually managing their states and events looks a lot cleaner.


Solution

  • Angular has different selectors:

    1. element-selector(app-child)
    2. class selector (.app-child)
    3. attribute selector ([app-child])

    The advantage of class and attribute selector is no extra selector is added, so use that.

    <table>
      <thead>
        <tr>
          <th>Data 1</th>
          <th>Data 2</th>
        </tr>
      </thead>
      <tbody>
        @for(item of items; track item.id) {
        <tr app-child [item]="item" (event1)="eventFunc.emit()"></tr>
        }
      </tbody>
    </table>
    

    Then change the selector in the child component.

    @Component({
      ...
      selector: '[app-child]',
      ...
    })
    exprt class ChildComponent {
      ...