【问题标题】:Multiple table rows as single component多个表格行作为单个组件
【发布时间】:2019-07-18 13:51:43
【问题描述】:

在单个 Angular 组件中拥有多个表行的方法是什么? 我想在给定列表的每个项目中显示两行,并将其放在 HTML 表中。

我尝试使用带有组件作为属性的 ng-template 以避免组件标记破坏表流,但在这种情况下输入将不起作用。理想情况下,我正在寻找一种从 dom 中删除组件标签的方法...

<table>
  <thead>
    <th>Name</th><th>City</th>
  </thead>
  <tbody>
    <ng-container app-located-person
                  *ngFor="let person of persons"
                  [person]="person">
    </ng-container>
  </tbody>
</table>

应用定位的人

<tr>
  <td>{{ person.name }}</td>
  <td>{{ person.city }}</td>
</tr>
<tr *ngIf="details">
  <td>Last connection</td>
  <td>{{ person.lastConnection }}</td>
</tr>

【问题讨论】:

  • 您尝试从 DOM 中删除组件标记是否有任何特殊原因?您可以简单地使用 它应该可以工作,如果您想隐藏/删除它,只需传递一个控制其可见性的 @Input 变量
  • 表格只允许与表格相关的标签(td、tr、th...)。组件标签会破坏其内部 tr 标签的预期表格行为
  • 你不能像这样使用&lt;ng-container app-located-person&gt;。在这种情况下,app-located-person 将是一个指令。如果我错了,请纠正我,但您不能将模板绑定到指令。 :) 为什么不在子组件中注入整个表格?
  • @MattWalterspieler 我已将指令的 html 绑定到 div 以保留之前的框架结构。显然 div 与 ng-container 不同。我将它定义为一个组件,但选择器设置为:[app-located-person],因此它将它应用于使用该特定属性的任何地方。
  • 我知道,这就是问题的目的;)我简化了示例,但我实际上希望行组件对显示内部数据进行一些调用,但前提是如果它扩大了

标签: javascript html angular


【解决方案1】:

我终于通过在组件节点上使用display: table-row-group; 来避免破坏表 dom 流:)

【讨论】:

【解决方案2】:

为什么不在ng-container 标签中包含tr?

<table>
  <thead>
    <th>Name</th><th>City</th>
  </thead>
  <tbody>
    <ng-container 
     *ngFor="let person of persons"
     [person]="person">
       <tr>
         <td>{{ person.name }}</td>
         <td>{{ person.city }}</td>
       </tr>
       <tr *ngIf="details">
         <td>Last connection</td>
         <td>{{ person.lastConnection }}</td>
       </tr>
    </ng-container>
  </tbody>
</table>

如果要使用组件:

<table>
  <thead>
    <th>Name</th><th>City</th>
  </thead>
  <tbody>
    <ng-container 
     *ngFor="let person of persons">
       <app-located-person [person]="person"></app-located-person>
    </ng-container>
  </tbody>
</table>

【讨论】:

    【解决方案3】:

    尝试以下方法:

    <table>
      <thead>
        <th>Name</th><th>City</th>
      </thead>
      <tbody>    
        <ng-container *ngFor="let person of persons">
          <tr>
            <td>{{person.name}}</td>
            <td>{{person.city}}</td>
          </tr>
          <tr *ngIf="person.lastConnection">
            <td>Last connection</td>
            <td>{{person.lastConnection}}</td>
          </tr>      
        </ng-container>
      </tbody>
    </table>
    

    Stackblitz:Link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 2016-04-06
      • 2019-11-16
      • 1970-01-01
      相关资源
      最近更新 更多