I need to change my tables paginators pageIndex and pageSize, my code works well when i use ViewChild, but i want to use signal query, when i use signal query i got this error;
Writing to signals is not allowed in a computed
or an effect
by default.
///@ViewChild('paginator') paginator: MatPaginator; -->this works
paginator = viewChild<MatPaginator>('paginator');
_onPaginationChange(event: PageEvent) {
const previousPageIndex = this.req.pageNumber - 1;
const previousPageSize = this.req.pageSize;
this.checkModifiedCellsAndCallback(() => {
this.req.pageNumber = event.pageIndex + 1;
this.req.pageSize = event.pageSize;
this.getTableData();
});
// Revert paginator state if the user cancels the action
if (this.modifiedCells.size > 0) {
setTimeout(() => {
paginator.pageIndex = previousPageIndex;
paginator.pageSize = previousPageSize;
});
}
}
You have to execute the signal method to access the element from the viewChild
.
After doing these changes. You might need to call cdr.detectChanges();
since we are modifying the signals inner properties so it’s not a proper signal update, so we need to call this, for change detection to fire and the changes to be updated. Mostly this will be needed when changeDetectionStrategy
is OnPush
.
paginator = viewChild<MatPaginator>('paginator');
cdr: ChangeDetectorRef = inject(ChangeDetectorRef);
_onPaginationChange(event: PageEvent) {
const previousPageIndex = this.req.pageNumber - 1;
const previousPageSize = this.req.pageSize;
this.checkModifiedCellsAndCallback(() => {
this.req.pageNumber = event.pageIndex + 1;
this.req.pageSize = event.pageSize;
this.getTableData();
});
// Revert paginator state if the user cancels the action
if (this.modifiedCells.size > 0) {
setTimeout(() => {
const paginator = this.paginator(); // <- execute the `viewChild` to access the paginator object.
paginator.pageIndex = previousPageIndex;
paginator.pageSize = previousPageSize;
this.cdr.detectChanges();
});
}
}
2