【问题标题】:Sorting Object's Attribute Angular Material排序对象的属性角度材质
【发布时间】:2021-03-20 21:33:03
【问题描述】:

我正在尝试使用 mat-sort-header 对 mat-table 进行排序。我可以使用字符串或数字等常见属性来做到这一点。

 <table #tablaClientes mat-table [dataSource]="dataSource" matSort multiTemplateDataRows>
  <!-- Id Column -->
  <ng-container matColumnDef="idIngreso">
    <th mat-header-cell *matHeaderCellDef mat-sort-header>Id Comprobante</th>
    <td mat-cell *matCellDef="let row">{{row.idIngreso}}</td>
  </ng-container>
  <!-- Proveedor Column -->
  <ng-container matColumnDef="idProveedor">
    <th mat-header-cell *matHeaderCellDef mat-sort-header>Nombre Proveedor</th>
    <td mat-cell *matCellDef="let row">{{row.idProveedor.nombre}}</td>
  </ng-container>
  <!-- Fecha Compra Column -->
  <ng-container matColumnDef="fechaCompra">
    <th mat-header-cell *matHeaderCellDef mat-sort-header>Fecha de Compra</th>
    <td mat-cell *matCellDef="let row">{{row.fechaCompra}}</td>
  </ng-container>
  <!-- Fecha Recepcion Column -->
  <ng-container matColumnDef="fechaRecepcion">
    <th mat-header-cell *matHeaderCellDef mat-sort-header>Fecha de Recepcion</th>
    <td mat-cell *matCellDef="let row">{{row.fechaRecepcion}}</td>
  </ng-container>
  <!-- Monto Total Column -->
  <ng-container matColumnDef="totalIngreso">
    <th mat-header-cell *matHeaderCellDef mat-sort-header>Monto Total</th>
    <td mat-cell *matCellDef="let row">{{row.totalIngreso |currency}}</td>
  </ng-container>

但是我不能按 idProveedor 排序,因为它是一个对象。

非常感谢!

【问题讨论】:

    标签: html angular angular-material mat-table


    【解决方案1】:

    更简单的方法是向您的数据源添加一个新属性并按此新属性排序,例如this SO(如果您不需要“idProveedor”对象,您的数据源可以转换为类似的对象

    this.data.forEach(x=>{
       x.proveedorNombre=x.idProveedor.nombre
       delete x.idProveedor
    }
    

    另一种解决方案是创建一个sortingDataAccesor

    this.dataSource.sortingDataAccessor = (item, property) => {
         if (property=="idProveedor")
             return item.nombre;
         if (property=="idIngreso")
            return item.idIngreso
         if (property=="fechaCompra")
            return item.fechaCompra
    
         ...
    }
    

    this stackblitz中的一个简单例子

    【讨论】:

      猜你喜欢
      • 2021-12-10
      • 2018-04-25
      • 1970-01-01
      • 2022-10-05
      • 2019-06-14
      • 2019-05-20
      • 2021-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多