Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 7 Grouping Data Using *ngfor

Right now i have data coming in like this in my angular application

https://stackblitz.com/edit/angular-ymmt4d

enter image description here

How can i group and order the data by State and County and display like below table

enter image description here

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>
like image 807
Pein Avatar asked Mar 05 '23 14:03

Pein


1 Answers

if you has the data ordered you can use let i=index and check if the before data is eauql using a conditional operator

<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>
like image 155
Eliseo Avatar answered Mar 15 '23 21:03

Eliseo