在ngFor中添加兄弟逻辑

时间:2017-04-18 13:22:23

标签: angular

我在角度模板中有一个表,其行是通过使用 ngFor 指令迭代对象生成的。示例代码:

<table *ngIf="results.length > 0" class="table table-hover">
  <thead>
    <tr>
      <th class="col-md-1">ID</th>
      <th class="col-md-3">Code</th>
      <th class="col-md-2">Type</th>
      <th class="col-md-4">Value(s)</th>
      <th class="col-md-2"><b class="invisible">.</b></th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let r of results">
      <td class="col-md-1">{{r.id}}</td>
      <td class="col-md-3">{{r.code}}</td>
      <td class="col-md-2">{{r.type}}</td>
      <td class="col-md-4">{{r.values}}</td>
      <td class="col-md-2">
        <button (click)="add(r.id)">Add</button>
      </td>
    </tr>

    <tr class="hidden"> // <----- The following lines needs to repeat for all iterations
      <td colspan="5">
        // Some other code
      </td>
    </tr>
  </tbody>
</table>

我的目的是在 ngFor 生成的每一行的下方获得一个完整的行,这样点击每行上的按钮,我就可以在包含的行的下方显示相应的行按钮。

这可以通过简单的方式实现吗?

2 个答案:

答案 0 :(得分:4)

使用ng-container,如:

<ng-container *ngFor="let r of results">
  <tr>...</tr>
  <tr>...</tr>
</ng-container>

答案 1 :(得分:0)

你应该能够做到这一点,表格应该仍然正常:

<table *ngIf="results.length > 0" class="table table-hover">
  <thead>
    <tr>
      ...
    </tr>
  </thead>
  <tbody>
    <div *ngFor="let r of results">
      <tr>
        ...
      </tr>
      <tr class="hidden">
        ...
      </tr>
    </div>
  </tbody>
</table>

或者更确切地说是另一个答案中提供的示意性正确的版本。