Use Primeng Async Datatable
07-09-2022HTML file
<div class="flex flex-col flex-auto min-w-0"> <!-- Main --> <div class="flex-auto p-6 sm:p-10 "> <p-table [value]="users" [lazy]="true" (onLazyLoad)="loadCarsLazy($event)" dataKey="id" [paginator]="true" [rows]="10" [totalRecords]="totalRecords" [loading]="loading"> <ng-template pTemplate="header"> <tr> <th *ngFor="let col of cols"> {{col.header}} </th> </tr> </ng-template> <ng-template pTemplate="body" let-car> <tr> <td *ngFor="let col of cols"> {{car[col.field]}} </td> </tr> </ng-template> </p-table> </div> </div>
Typescript Code
import { AfterViewInit, Component, Input, OnDestroy, OnInit, SimpleChanges, ViewChild, ViewEncapsulation } from '@angular/core'; import {FormBuilder, Validators} from '@angular/forms'; import {MatDialog} from '@angular/material/dialog'; import {LoadSelectionService} from '../../../backend-api/load-selection.service'; import {map, Observable, Subject, take, takeUntil, tap} from 'rxjs'; import {AgGridAngular} from 'ag-grid-angular'; import {UserService} from './user.service'; import {CellClickedEvent, ColDef, GridReadyEvent, RowModelType} from 'ag-grid-community'; import {ApiResponse} from '../../../backend-api/models/api-response'; @Component({ selector: 'admin-user', templateUrl: './user.component.html', encapsulation: ViewEncapsulation.None }) export class UserComponent implements OnDestroy { users: any[]; totalRecords: number; cols = [ {field: 'username', header: 'UserId'}, {field: 'firstName', header: 'First Name'}, {field: 'lastName', header: 'Last Name'}, {field: 'email', header: 'Email'}, {field: 'enabled', header: 'Enabled'}, ]; loading: boolean; private subject = new Subject<boolean>(); constructor(private userService: UserService) { } public loadCarsLazy($event) { setTimeout(() => { this.userService.list({lazyEvent: JSON.stringify($event)}).pipe( map(apiResponse => { this.users = apiResponse.data.rows; this.totalRecords = apiResponse.data.records; this.loading = false; }), takeUntil(this.subject) ).subscribe(); },10); } ngOnDestroy(): void { this.subject.next(true); this.subject.complete(); } }
User Service
import { Injectable } from '@angular/core'; import {map, mergeMap, Observable, of, switchMap, tap} from 'rxjs'; import {ApiResponse} from '../../../backend-api/models/api-response'; import {HttpClient, HttpParams} from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class UserService { constructor(private httpClient: HttpClient) { } list(params): Observable<ApiResponse> { return this.httpClient.get<ApiResponse>(`admin/getUsers?`, {params: new HttpParams({ fromObject: {...params} })}); } }