最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Mar 24 at 5:48 Naren Murali 60.3k5 gold badges44 silver badges77 bronze badges asked Mar 22 at 5:02 RajRaj 253 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

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 {
  ...
发布评论

评论列表(0)

  1. 暂无评论