Angular ngFor跨越两行(展开/折叠)

时间:2017-05-22 16:45:30

标签: angular html-table expand ngfor

我有一个角度应用程序。我需要在表格中显示数据列表。我已经在表的TR元素上应用了ngFor。但是,当展开每一行时,必须显示另一行以及有关该项目的其他详细信息。

折叠视图: enter image description here

扩展视图: enter image description here

代码:

<table>
  <thead>
  <tr>Header here</tr>
  </thead>
  
  <tbody>
    <tr *ngFor="let item of results">
      + Collapsed Row
      <!-- How do I display the expanded row and display additional details when + symbol is clicked? -->
    </tr>
    
  </tbody>
</table>

2 个答案:

答案 0 :(得分:5)

如果你只想要一个简单的展开和折叠行,那么一个简单的ngIf就可以解决这个问题:

<tr *ngFor="let item of results">
  <div (click)="item.expanded=!item.expanded">+ Collapsed Row</div>
  <span *ngIf="item.expanded">This is an expanded content</span>
</tr>

但是,如果您希望一次只展开一行,则需要跟踪哪一行展开。

在你的HTML中:

<tr *ngFor="let item of results; let $index=index;">
  <div (click)="expandRow($index)">+ Collapsed Row</div>
  <span *ngIf="$index === expandedIndex">This is an expanded content</span>
</tr>

在组件中,初始化名为expandedIndex的变量,其值为-1。这可确保在组件出现时折叠所有行。您可以在构造函数级别或ngOnInit执行此操作,但这并不重要:

constructor(public expandedIndex:number){
   this.expandedIndex=-1;
}

然后,有一个名为expandRow的命名函数:

  expandRow(index: number): void {
    this.expandedIndex = index === this.expandedIndex ? -1 : index;
  }

答案 1 :(得分:1)

我遇到了同样的问题,我没有找到任何好的解决方案。但经过深入研究后,我发现了这个容器并且效果很好。你可以在行动中看到它

https://plnkr.co/edit/F8ohXKLHvvbHXAqGESQN?p=preview

  <ng-container *ngFor="let obj of posts">
            <tr>
                <td>
                    <button (click)="openCloseRow(obj.id)">
                        <span *ngIf="rowSelected!=obj.id; else close">Open</span>
                          <ng-template #close>
                            <span>Close</span>
                            </ng-template>
                    </button>
                </td> 
              <td>{{obj.date}}</td>
              <td>
                  {{obj.subject}}
              </td>
              <td>{{obj.numComents}}</td>
            </tr>
            <tr *ngIf="rowSelected==obj.id">
                <td></td>
                <td colspan="4">
                    <table class="table table-striped">
                        <thead>
                            <tr>                                   
                                <th style="width:15%;">Comment</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr *ngFor="let q of obj.comments">                                  
                                <td style="width:15%;">{{q}}</td>
                            </tr>
                        </tbody>
                    </table>
                </td>
            </tr>
          </ng-container>
相关问题