Search code examples
javascriptangularfirebasegoogle-cloud-firestoreangularfire2

How can I make sort table work with Angular 8 + data from firebase?


I have an angular PWA with a material table with data from firebase, the data is showned and the paginator is working but I also want to sort its data, but mat-sort doesn't work. It shows the arrow to sort the data, but when clicking the arrow the data is not sorted.

I have followed the documentation from Angular Material.

The table in the component template:

        <ng-container matColumnDef="movimento">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>Tipo de movimento</th>
            <td mat-cell *matCellDef="let movimento"> {{movimento.mapValue.fields.tipo_movimento.stringValue}}
            </td>
        </ng-container>

        <ng-container matColumnDef="valor">

            <th mat-header-cell *matHeaderCellDef mat-sort-header>Valor</th>
            <td mat-cell *matCellDef="let movimento">
                {{movimento.mapValue.fields.valor.doubleValue | number:'1.1-2'}}
                {{movimento.mapValue.fields.valor.integerValue}} €
            </td>
        </ng-container>

        <ng-container matColumnDef="data">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>Data</th>
            <td mat-cell *matCellDef="let movimento"> {{movimento.mapValue.fields.data.timestampValue | date}}
            </td>
        </ng-container>

        <ng-container matColumnDef="desc">
            <th mat-header-cell *matHeaderCellDef mat-sort-header>Descrição</th>
            <td mat-cell *matCellDef="let movimento"> {{movimento.mapValue.fields.desc.stringValue}}</td>
        </ng-container>

        <tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></tr>
        <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>


    </table>
    <mat-paginator [pageSizeOptions]="[10, 20, 40]" showFirstLastButtons></mat-paginator>

The Component:

@Component({
  selector: 'app-movimentar',
  templateUrl: './visualizar-movimentos.component.html',
  styleUrls: ['./visualizar-movimentos.component.css']
})
export class VisualizarMovimentosComponent implements OnInit {
  user: firebase.User;

  userData;

  displayedColumns: string[] = ['movimento', 'valor', 'data', 'desc'];

  dataSource = new MatTableDataSource<Movimentos>();


  @ViewChild(MatPaginator, { static: false })
  set paginator(value: MatPaginator) {
    this.dataSource.paginator = value;
  }

  @ViewChild(MatSort, { static: false }) sort: MatSort;


  constructor(private auth: AuthService,
    private router: Router,
    private afs: AngularFirestore) { }

  ngOnInit() {
    this.auth.getUserState()
      .subscribe(user => {
        this.user = user;

        this.getUserData();
      });

  }

  /* loadLessonsPage() {
    this.dataSource._orderData;
    debugger
  } */

  getUserData(): void {
    this.auth.getUserData(this.user.uid)
      .subscribe(user => {
        this.userData = user;

        this.dataSource = new MatTableDataSource(this.userData._document.proto.fields.movimentos.arrayValue.values);

        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;

      });


  }

  login() {
    this.router.navigate(['login']);
  }

  logout() {
    this.auth.logout();
    this.router.navigate(['inicio']);
  }

  register() {
    this.router.navigate(['/register']);
  }

  trackByUid(index, item) {
    return item.uid;
  }



}```

Thanks for the help in advance.

Solution

  • The problem was with the data from firebase, it was not compatible with the mat sort. To solve it you need a map like this one:

    Here's the map

        return data.reduce((acc, value) => {
          return [
            ...acc,
            Object.entries(value.mapValue.fields).reduce((accValue, [key, value]) => {
              return {
                ...accValue,
                [key]: Object.values(value)[0]
              }
            }, {})
          ]
        }, [])
      }