Last active
December 18, 2021 11:10
-
-
Save NazemMahmud/1eea689550c7fd4d3eba69e50a3ae4cf to your computer and use it in GitHub Desktop.
Angular Material: main component ts file for pagination sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {AfterViewInit, Component, OnDestroy, OnInit, ViewChild} from '@angular/core'; | |
import {Subject} from 'rxjs'; | |
import {takeUntil} from 'rxjs/operators'; | |
import {MatTableDataSource} from '@angular/material'; | |
import {MainService} from './service/main.service'; | |
// this will be your shared component path | |
import {BasicPaginationComponent} from '../shared/components/basic-pagination/basic-pagination.component'; | |
@Component({ | |
selector: 'main-component', | |
templateUrl: './main.component.html', | |
styleUrls: ['./main.component.scss'], | |
provider: ['MainService'] | |
}) | |
export class MainComponent implements OnInit, AfterViewInit, OnDestroy { | |
@ViewChild(BasicPaginationComponent, {static: true}) paginator: BasicPaginationComponent; | |
private _unsubscribeAll: Subject<any>; | |
isLoading = false; // show data table if it is false, here you may use a loader when it is true | |
displayedColumns: string[] = ['name', 'email']; | |
dataSource: MatTableDataSource<any>; // mat table data source | |
// for pagination | |
total: any; | |
pageOffset: any; | |
pageIndex: any; | |
constructor(private _service: MainService) { | |
this._unsubscribeAll = new Subject(); | |
} | |
ngOnInit(): void { | |
this.isLoading = true; | |
this.pageOffset = 10; | |
this.pageIndex = 1; | |
this.orderBy = 'desc'; | |
} | |
// call the service for http call | |
getValues(): void { | |
this.isLoading = true; | |
this._service.getAll(this.pageOffset, this.pageIndex, this.orderBy) | |
.pipe(takeUntil(this._unsubscribeAll)).subscribe(res => { | |
this.dataSource = new MatTableDataSource(res.data); | |
this.total = res.meta.total; | |
this.isLoading = false; | |
}); | |
} | |
ngAfterViewInit(): void { | |
// after paginate state update in pagination component | |
this.paginator.paginate.pipe(takeUntil(this._unsubscribeAll)).subscribe(paginator => { | |
this.pageIndex = paginator.page; | |
this.pageOffset = paginator.pageOffset; | |
this.getValues(); | |
}); | |
} | |
ngOnDestroy(): void { | |
// Unsubscribe from all subscriptions | |
this._unsubscribeAll.next(); | |
this._unsubscribeAll.complete(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment