Ngx-Datatable排序列时rowIndex值异常及切换开关属性问题
Hey there! I’ve run into both of these ngx-datatable quirks before, so let’s break down how to fix them for you.
1. Incorrect rowIndex Value After Column Sorting
The problem here is that ngx-datatable’s rowIndex refers to the current rendered position of the row, not its original index in your dataset. When you sort columns, the rendered order changes, so rowIndex shifts along with it—this is expected behavior, but not helpful if you need the original data index.
Solution: Use a Custom Original Index Field
Instead of relying on rowIndex, add an explicit original index property to your data when you first load it. This way, you’ll always have access to the unchanging original position, even after sorting/filtering:
Component Code:
// When initializing your dataset loadData() { // Assume your raw data comes from an API or local source const rawData = [/* your data objects */]; // Map each item to include an originalIndex this.tableData = rawData.map((item, index) => ({ ...item, originalIndex: index // This stays fixed regardless of sorting })); }
Template Usage:
<ngx-datatable-column name="Row #"> <ng-template ngx-datatable-cell-template let-row="row"> {{ row.originalIndex + 1 }} <!-- Display original position --> </ng-template> </ngx-datatable-column>
Now you’ll always get the original index, no matter how the table is sorted.
2. Implementing a Toggle Switch to Modify Column Properties
From your partial code, it looks like you’re using Angular Material’s mat-slide-toggle to update the activation_status property. Let’s flesh out this implementation to ensure it works reliably, including triggering table updates when the status changes.
Complete Template Code:
<ngx-datatable-column name="Activation Status" prop="activation_status"> <ng-template ngx-datatable-cell-template let-value="value" let-row="row"> <mat-slide-toggle color="accent" [checked]="value === 'ACTIVATED'" (change)="updateActivationStatus(row)"> {{ value === 'ACTIVATED' ? 'Activated' : 'Deactivated' }} </mat-slide-toggle> </ng-template> </ngx-datatable-column>
(Note: We removed the redundant *ngIf checks by using [checked] binding instead—cleaner and more maintainable!)
Component Code for Status Update:
updateActivationStatus(row: any) { // Toggle the status value row.activation_status = row.activation_status === 'ACTIVATED' ? 'DEACTIVATED' : 'ACTIVATED'; // Trigger table refresh (ngx-datatable relies on reference changes) this.tableData = [...this.tableData]; }
By spreading the array into a new instance ([...this.tableData]), we tell Angular to detect the data change and refresh the table row—this ensures the toggle’s state and display text update immediately.
内容的提问来源于stack exchange,提问作者Luca Brasi

