Search code examples
angularangular-material2angular-material-table

Accessing next previous row while rendering Angular Material table


<ng-container cdkColumnDef="weight">
  <th cdk-header-cell *cdkHeaderCellDef> Weight </th>
  <td cdk-cell *cdkCellDef="let element"> {{element.weight}} </td>
</ng-container>

I want to display {{element.weight} + element of previous row.weight} like a rolling weight total. What is the syntax? Working sample source is taken from here.


Solution

  • I have implemented the Rolling weight total by custom logic, Please go through and comment if you have any doubts!

    Result

    Stack blitz link

    In html

        <!-- Weight Column -->
    <ng-container cdkColumnDef="weight">
        <th cdk-header-cell *cdkHeaderCellDef> Weight </th>
        <td cdk-cell *cdkCellDef="let element"> {{getElementWeight(element)}} </td>
        <!--  <td cdk-cell *cdkCellDef="let element"> {{element.weight}} </td> -->
    </ng-container>
    

    In ts

    declare global {
    interface Array < T > {
        getSummedWeight(): any;
        containsElement(e: any): any;
         }
      }
    
        custom:any = [];
    getElementWeight(e) {
        if (this.custom.containsElement(e)) {
            this.custom = [];
            console.log("########contains#####")
        }
        this.custom.push({
            'position': e.position,
            'name': e.name,
            'weight': e.weight,
            'newweight': e.weight + (this.custom.length == 0 ? 0 : this.custom.getSummedWeight())
        })
        console.log(this.custom)
        return this.custom.length == 0 ? 0 : this.custom[this.custom.length - 1].newweight
    
    }
    
    
      if (!Array.prototype.getSummedWeight) {
    Array.prototype.getSummedWeight = function(): any {
        let totalWeight = this.length == 1 ? this[this.length - 1].weight :
            this[this.length - 1].weight;
        return totalWeight;
        }
    }
      if (!Array.prototype.containsElement) {
    Array.prototype.containsElement = function(e): any {
        for (let i = 0; i < this.length; i++) {
            if (this[i].position === e.position)
                return true;
        }
        return false;
       }
     }