渲染Component的内容,不带标签

时间:2017-12-18 16:59:36

标签: javascript html angular typescript angular5

我需要使用Angular 2+将多级数据渲染到单个平面表中。但是,数据的每个部分都由嵌套组件呈现。由于组件具有自己的标记,因此它是<tbody/>的无效子项。

如何渲染组件的内容而不渲染自己的标签?

以下是一个简化示例:

@Component({
  selector: 'app-table-section',
  template: '<tr><td><h3>{{heading}}</h3></td></tr>' + 
        '<tr *ngFor="let i in items">{{i}}<td></td></tr>',
})
export class TableSectionComponent {
    @Input() heading: string;
    @Input() items: string[];
}

使用者:

@Component({
  selector: 'app-date-table',
  template: '<table>' +
  '  <thead><tr><th>Item Name</th></tr></thead>' +
  '  <tbody>' +
  '    <app-table-section *ngFor="let section of data"' +
  '                       [heading]="section.name"' +
  '                       [items]="sectons.items"></app-table-section>' +
  '  </tbody>' +
  '</table>',
})
export class CustomerListItemComponent {
  data = [
    {name:'Foo', items:['1', '2']},
    {name:'Bar', items:['a', 'b', 'c']},
  ]

  constructor() {
  }
}

以上将使用for循环的结果只占用1个表格单元而不是多行,如下所示:

<table>
  <thead><tr><th>Item Name</th></tr></thead>
  <tbody>
  <app-table-section>
    <tr>
      <td><h3>Foo</h3></td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
    </tr>
  </app-table-section>
  <app-table-section>
    <tr>
      <td><h3>Bar</h3></td>
    </tr>
    <tr>
      <td>a</td>
      <td>b</td>
      <td>c</td>
    </tr>
  </app-table-section>
  </tbody>
</table>

我希望能够:

<table>
  <thead><tr><th>Item Name</th></tr></thead>
  <tbody>
    <tr>
      <td><h3>Foo</h3></td>
    </tr>
    <tr>
      <td>1</td>
      <td>2</td>
    </tr>
    <tr>
      <td><h3>Bar</h3></td>
    </tr>
    <tr>
      <td>a</td>
      <td>b</td>
      <td>c</td>
    </tr>
  </tbody>
</table>

我已阅读Angular2 : render a component without its wrapping tag 及其接受的答案discussion page,但无法找到上述所需内容。

1 个答案:

答案 0 :(得分:0)

我最终使用了CSS的display: contents。截至2018年9月,主要浏览器(Edge除外)现在(至少部分)支持此功能。 (参考:caniuse.com

:host {
  display: contents;
}
相关问题