I am working on an Angular application with ngx-datatable installed and working. I have a Supplier object and I need to display a table using ngx-datatable where some columns are showing some properties of the object and some columns are showing values calculated on the fly on object's properties.
This is my Supplier class:
import { Invoice } from '../../invoice/model/invoice';
import { MasterData } from '../../master-data/model/master-data';
export class Supplier {
"createdAt": Date;
"createdBy": string;
"updatedAt": Date;
"updatedBy": string;
"id": string;
"masterData": MasterData;
"invoices": Invoice[];
}
This is the Invoice class:
export class Invoice{
"id": string;
"number": string;
"year": number;
"date": Date;
"amount": number;
}
Now I want to show a table containing a list of suppliers with the following columns: id, createdAt, createdBy, totalAmountOfInvoices, totalNumberOfInvoices.
My problem comes with the last two columns which I don't know how to handle properly.
ngx-datatable is expecting a rows[]
and a columns[]
in the component, but while I'm passing a Supplier[]
for the rows, I don't know what I should use for the calculated columns.
What is the best way to display that data? Should I calculate those values and inject them in supplier object when I retrieve the object in the service, or there's a better way to solve my problem?
I've found a solution. Just use the ng-template instead of passing a column[]
to the table. This way I can call functions in my component.
<ngx-datatable [rows]="supplier" class="material">
<ngx-datatable-column>
<ng-template let-column="column" ngx-datatable-header-template>
<span (click)="sort()">Name</span>
</ng-template>
<ng-template let-row="row" ngx-datatable-cell-template>
{{row.masterData.name}}
</ng-template>
</ngx-datatable-column>
<ngx-datatable-column>
<ng-template let-column="column" ngx-datatable-header-template>
Invoices({{currentYear}})
</ng-template>
<ng-template let-row="row" ngx-datatable-cell-template>
{{getNumberOfInvoicesCurrentYear(row)}}
</ng-template>
</ngx-datatable-column>
<ngx-datatable-column>
<ng-template let-column="column" ngx-datatable-header-template>
Invoices total amount ({{currentYear}})
</ng-template>
<ng-template let-row="row" ngx-datatable-cell-template>
{{getNumberOfInvoicesCurrentYear(row)}}
</ng-template>
</ngx-datatable-column>
</ngx-datatable>