I am using angular-datatables v14.0.2 in my Angular project and I am having a problem when adding new elements to my datatable. Every time I add a new element to my data array, it appears in the first row of my datatable instead of in the last row.
I have tried several solutions, such as using the spread operator (...) to create a copy of the array and add the new element at the end, using the destroy method and reinitializing the datatable after adding a new element, and disabling sorting on all columns and in the DataTables configuration. However, none of these solutions have worked and the new elements still appear in the first row of my datatable.
Here is the code I am using to add new elements to my datatable:
ngOnInit(): void {
this.data = [
{id: 2, firstName: 'Jose 2', lastName: 'dos'},
{id: 1, firstName: 'Jose 1', lastName: 'uno'},
{id: 3, firstName: 'Jose 3', lastName: 'tres'},
];
this.dtOption = {
order: [],
};
}
more(): void {
var sa = this.data[this.data.length - 1].id;
this.data.push({id: (sa + 1), firstName: 'dsds', lastName: new Date()});
this.dtElement.dtInstance.then((dtInstance: any) => {
dtInstance.clear();
dtInstance.rows.add(this.data);
dtInstance.draw();
});
}
also try this:
more(): void {
var sa = this.data[this.data.length - 1].id;
this.data.push({id: (sa + 1), firstName: 'dsds', lastName: new Date()});
this.dtElement.dtInstance.then((dtInstance: any) => {
dtInstance.destroy();
this.dtTrigger.next();
});
}
my html:
<button type="button" class="btn waves-effect waves-light blue" (click)="more()">
new
</button>
<table id="second-table" datatable [dtOptions]="dtOption" [dtTrigger]="dtTrigger" class="row-border hover">
<thead>
<tr>
<td>id</td>
<td>nombre</td>
<td>apellido</td>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of data">
<td>{{item.id}}</td>
<td>{{item.firstName}}</td>
<td>{{item.lastName}}</td>
</tr>
</tbody>
</table>
Does anyone know why new items appear in the first row of my datatable? I want it to appear in the last row, I want it to respect the order it is in in my array, how can I fix this problem?