javascript - 使用 *ngFor 在 Angular 7 中分組資料
現在我在我的 Angular 應用程式中有像這樣進來的數據
https://stackblitz.com/edit/angular-ymmt4d
我如何能依據州和縣來分組和排序數據,並像下表一樣顯示
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
data = [
{ state: 'MN', county: '1', item: 0.297 },
{ state: 'MN', county: '1', item: 0.04 },
{ state: 'CA', county: '2', item: 0.019 },
{ state: 'MN', county: '1', item: 0.0374 },
{ state: 'CA', county: '2', item: 0.037 }
]
} <table >
<tr>
<th>State</th>
<th>County</th>
<th>Item</th>
</tr>
<ng-container *ngFor="let dataitem of data">
<tr>
<td>{{dataitem.state}}</td>
<td>{{dataitem.county}}</td>
<td>{{dataitem.item}}</td>
</tr>
</ng-container>
</table>答案#1
如果你有排序好的資料,你可以使用 let i=index 並使用條件運算子檢查前一筆資料是否相等
<ng-container *ngFor="let dataitem of data;let i=index">
<tr>
<td>{{i>0 && data[i-1].state==dataitem.state?'':dataitem.state}}</td>
<td>{{i>0 && data[i-1].county==dataitem.county?'':dataitem.county}}</td>
<td>{{dataitem.item}}</td>
</tr>
</ng-container>
答案#2
使用 lodash 將你的資料轉換成多個陣列。
https://lodash.com/docs/4.17.11#groupBy
import { groupBy } from 'lodash-es'
const states = groupBy(data, 'state')
在你的表格中,你可以有多個 tbody
<tbody *ngFor="let state of states">...</tbody>

