ngx-think-components
v1.0.2
Published
``` import { Component, inject } from '@angular/core';
Readme
Ejemplo de como funcionaria la capa de la logica component.ts
import { Component, inject } from '@angular/core';
import { TestComponent,ToolbarComponent, DynamicTableComponent,
PaginationComponent, PaginationInterface,
ColumnsGrid , PaginationResponseInterface,
MessagesService,
CrudService,
MessagesToastService
} from 'ngx-think-components'
@Component({
selector: 'app-root',
standalone: true,
imports: [TestComponent, DynamicTableComponent, ToolbarComponent, PaginationComponent],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'app-test-lib';
data: any[] = [
{
"idPartyType":1,
"partyTypeDescription": "Descripcion",
"createdAt" : "01/08/2025",
"updatedAt" : "10/08/2025"
}
];
showLoad:boolean = false;
get paginatedData(): any[] {
return this.data;
}
columns: ColumnsGrid[] = [
{ key: 'idPartyType', title: 'ID', align: 'center', filterable: true, width: '80px',type: 'number' },
{ key: 'partyTypeDescription', title: 'Descripción', align: 'left' ,filterable: true, width: '240px', type: 'text' },
{ key: 'createdAt', title: 'Creado', align: 'right' , filterable: true, width: '180px', type: 'date' },
{ key: 'updatedAt', title: 'Actualizado', align: 'right', filterable: true, width: '180px', type: 'date' },
];
// Paginación
page: number = 0;
pageSize: number = 10;
totalElements: number = 0;
totalPages: number = 0;
pagination:PaginationInterface = {
pageNumber: this.page,
rowsPerPage: this.pageSize,
filters: [],
sorts: []
};
readonly messagesService = inject(MessagesService);
readonly crudService = inject(CrudService);
readonly toast = inject(MessagesToastService);
constructor(){
}
loadPaginatedData() {
const url = 'environment.dominio' + '/party-type/pagination';
this.updatePagination(); // Actualizar la paginación antes de cargar los datos
this.showLoad = true;
this.crudService.pagination<PaginationResponseInterface>(url, this.pagination).subscribe({
next: (response) => {
const resp = response;
this.data = resp.content as any[];
this.page = resp.pageable.pageNumber;
this.totalElements = resp.totalElements;
this.totalPages = resp.totalPages;
this.showLoad = false;
},
error: (error) => {
this.showLoad = false;
this.toast.show(error.mensaje || 'Ocurrió un error al cargar los datos',
'toast-body bg-danger text-white',
3000
);
}
});
}
setPage(page: number) {
if (page >= 0 && page <= this.totalPages) {
this.page = page;
this.loadPaginatedData(); // Cargar datos paginados al cambiar de página
}
}
updatePagination() {
this.pagination.pageNumber = this.page;
this.pagination.rowsPerPage = this.pageSize;
this.pagination.filters = this.pagination.filters || [];
this.pagination.sorts = this.pagination.sorts || [];
}
onSort(event: { key: string, direction: 'asc' | 'desc' }) {
const _sort = {
colName: event.key,
direction: event.direction
};
this.pagination.sorts = [ _sort ];
this.page = 0;
this.pagination.pageNumber = this.page;
this.loadPaginatedData(); // Cargar datos paginados después de ordenar
}
onFilter(filter: {key:string, operator:string,value:string} ){
console.log(filter)
if(filter.value == null){
const index = this.pagination.filters.findIndex(obj => obj.field === filter.key);
if(index !== -1){
this.pagination.filters.splice(index,1);
this.loadPaginatedData();
return;
}
}
const _filter = {
field : filter.key,
value : filter.value
};
this.pagination.filters.push(_filter);
this.loadPaginatedData();
}
onEdit(row: any) {
// this.router.navigate(['desktop/tipo-documento-identidad-edit', row.data.idDocumentIdentificacion]);
}
onDelete(row: any) {
this.messagesService.message_question(
'question',
'Confirmar Eliminación',
`¿Está seguro de eliminar el tipo de documento de identidad: ${row.data.documentIdentificationDescription}?`,
'Eliminar',
'Cancelar'
).then((result) => {
if (result) {
//const url = `${environment.dominio}/document-identification`;
const url = `/document-identification`;
this.crudService.delete(url, row.data.idDocumentIdentificacion).subscribe({
next: () => {
this.toast.show('Tipo de documento de identidad eliminado correctamente', 'toast-body bg-success text-white', 3000);
this.loadPaginatedData();
},
error: (error) => {
this.toast.show(error.mensaje || 'Ocurrió un error al eliminar el tipo de documento de identidad',
'toast-body bg-danger text-white',
6000
);
}
});
}
});
}
onPageChange(page: number) {
this.setPage(page);
}
pageSizeChange(size: number) {
debugger
this.pageSize = size;
this.page = 0; // Reset to first page when changing page size
this.loadPaginatedData(); // Reload data with new page size
}
}Ejemplo del html
<app-toolbar></app-toolbar>
<app-dynamic-table
[columns]="columns"
[data]="paginatedData"
[showActions]="true"
[showLoad]="showLoad"
(sort)="onSort($event)"
(filter)="onFilter($event)"
(edit)="onEdit($event)"
(delete)="onDelete($event)"
></app-dynamic-table>
<app-pagination
[totalItems]="totalElements"
[pageSize]="pageSize"
[page]="page"
(pageChange)="onPageChange($event)"
(pageSizeChange)="pageSizeChange($event)"
></app-pagination>
en app.config.ts
Agregar
provideHttpClient(withInterceptors([LoggerInterceptor])),
deberia quedar:
export const appConfig: ApplicationConfig = {
providers: [provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
provideHttpClient(withInterceptors([LoggerInterceptor])),
]
};El codigo de LoggerInterceptor, este es parte de la libreria:
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { LoggerInterceptor } from 'ngx-think-components';
export const LoggerInterceptor: HttpInterceptorFn = (req , next) => {
let idToken = sessionStorage.getItem("auth_token");
if (idToken) {
const token = 'Bearer ' + idToken;
const cloned = req.clone({
headers: req.headers.set('Authorization', token),
});
return next(cloned);
}
return next(req);
}
```