Home > Software design >  How do I bind angular material table values apart from their names?
How do I bind angular material table values apart from their names?

Time:04-10

I have an angular material table in my HTML, and I used as example expandable table because it suits me more than other types. This exact table also uses binding column/row names to array of strings called "columnsToDisplay".

<table mat-table
       [dataSource]="dataSource"
       multiTemplateDataRows
       >
<ng-container matColumnDef="{{column}}" *ngFor="let column of columnsToDisplay">
    <th mat-header-cell *matHeaderCellDef> {{column}} </th>
    <td mat-cell *matCellDef="let element"> {{element[column]}} </td>
  </ng-container>

...

tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
  <tr mat-row *matRowDef="let element; columns: columnsToDisplay;"
      
      [class.example-expanded-row]="expandedElement === element"
      (click)="expandedElement = expandedElement === element ? null : element">
  </tr>
  <tr mat-row *matRowDef="let row; columns: ['expandedDetail']" ></tr>
</table>

However properties that I want to show in this table don't have same names as properties that name columns. While properties that name columns look like this:

  columnsToDisplay = [__('TBL.pipeSectionName'), __('TBL.pipeSectionLoss'), __('TBL.pipeSectionType'), __('TBL.pipeSectionLength')]

Columns that have the needed values are part of an array of objects. How do I make values show up regardless of how columns are named in this table?

CodePudding user response:

You can do something like this

columnsToDisplay2 = [

    { label: 'Weird name label', value: 'name' },
    { label: 'Weird weight label', value: 'weight' },
    { label: 'Weird symbol label', value: 'symbol' },
    { label: 'Weird position label', value: 'position' },
  ];

and on the the html:

  <ng-container
    matColumnDef="{{column.value}}"
    *ngFor="let column of columnsToDisplay2"
  >
    <th mat-header-cell *matHeaderCellDef>{{column.label}}</th>
    <td mat-cell *matCellDef="let element">{{element[column.value]}}</td>
  </ng-container>

Here is a stackblitz with it running https://stackblitz.com/edit/angular-6b8rmt?file=src/app/table-expandable-rows-example.html

  • Related