Angular 6 : Load more data on page scroll
Instead of pagination, Load more data on page scroll.
Installation
npm install ngx-infinite-scroll --save
Register
Update app.module.ts
import { InfiniteScrollModule } from 'ngx-infinite-scroll';
imports: [
...,
InfiniteScrollModule,
...
],
Model
export class country{
ID : number;
Name : string;
}
export class countries{
ID : number;
Name : string;
constructor(item?: country) {
if (item != undefined) {
for (let key in item) {
try { this[key] = item[key]; }
catch (e) { }
}
}
}
}
Component.ts
export class DemoScrollDataComponent implements OnInit {
page: number = 1;
records: country[] = [];
constructor(private countryService : CountryService) { }
ngOnInit() {
this.getData(0);
}
getData(page : Number) {
console.log(this.page);
this.countryService.getCountry(this.page).subscribe((res) => this.onSuccess(res));
}
// When we got data on a success
onSuccess(res) {
console.log(res);
if (res != undefined) {
res.forEach(item => {
this.records.push(new countries(item));
});
}
}
onScrollDown (ev) {
console.log('scrolled down!!', ev);
this.page = this.page + 1;
this.getData(this.page);
}
onUp(ev) {
console.log('scrolled up!', ev);
}
}
HTML
<div class="search-results"
infinite-scroll
[infiniteScrollDistance]="0"
[infiniteScrollUpDistance]="10"
(scrolled)="onScrollDown()"
(scrolledUp)="onUp()">
<div *ngFor="let item of records" style="padding:20px">
{{ item.ID }} - {{ item.Name }}
</div>
</div>
Service
export class CountryService {
constructor(private http:HttpClient) { }
getCountry(pageNumber : Number): Observable<country[]> {
return this.http.get<country[]>('http://localhost/DemoApp.API/api/CountryListPage?pageNumber='+ pageNumber)
}
}
Enjoy !!!
:)
No comments:
Post a Comment