Me gustaría acceder a la página actual de datos de angular-datatables, por lo que estoy usando DataTableDirective como se muestra a continuación:
@ViewChild(DataTableDirective, { static: false }) dtElement: DataTableDirective; dtData: {id: number, name: string, selected: boolean}[]; selectAll(): void { this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => { dtInstance.rows({ page: 'current' }).every(function() { const id = this.data()[0]; // statement below not working as function override the `this` keyword // thus I can't refer to the dtData declared in global scope. const currentRow = this.dtData.find(item => item.id === id); currentRow.selected = true; }); }); } La función selectAll() se activará al hacer clic en el botón, dtInstance.rows({ page: 'current' }).every() recorrerá cada fila de la tabla de datos de la página actual.
Compruebo el código fuente de la función every() , tiene la siguiente firma de función:
/** * Iterate over each selected row, with the function context set to be the row in question. Since: DataTables 1.10.6 * * @param fn Function to execute for every row selected. */ every(fn: (this: RowMethods, rowIdx: number, tableLoop: number, rowLoop: number) => void): Api; Como puede ver, declara this como variable de RowMethods , es por eso que puedo acceder a los datos con this.data() , pero esto crea un problema donde no puedo referirme al contexto global de this dentro de este anónimo función, por lo tanto, me gustaría "cambiar el nombre" del nombre de la variable de this , lo probé con el siguiente código:
dtInstance.rows({ page: 'current' }).every(function(a: DataTables.RowMethods, b: number, c: number, d: number) { console.log(a.data()); });Pero obteniendo error
Argument of type '(a: RowMethods, b: number, c: number, d: number) => void' is not assignable to parameter of type '(this: RowMethods, rowIdx: number, tableLoop: number, rowLoop: number) => void'. ¿Puedo saber qué hice mal aquí? Sospecho que el problema está en el tipo de datos RowMethods , de alguna manera el compilador trata DataTables.RowMethods de manera diferente con RowMethods , pero no sé qué puedo hacer con esto. ¡Cualquier ayuda o solución sería apreciada!
¿Has probado con la función de flecha => para mantener this en el contexto global?
dtInstance.rows({ page: 'current' }).every((a: DataTables.RowMethods, b: number, c: number, d: number) => { console.log(this); console.log(a.data()); });