install and save
npm install ngx-infinite-scroll --save
Here I have used the two material components to hold images data into card-component and a toolbar which contains the title of my single page application, additionally i have used division tag to hold list of images to render inside card-component.
As you can see in my component code I have created several methods, and the primary method is onScroll().
npm install ngx-infinite-scroll --save
To implement infinite scroll, let's first design our user interface, for that open app.component.html and paste the below code.
- <mat-toolbar color="accent">
- <span>Manav Pandya - C#Corner</span>
- <span class="demo-toolbar"></span>
- </mat-toolbar>
- <mat-card>
- <div class="container">
- <div class="row" infiniteScroll [infiniteScrollDistance]="2" [infiniteScrollThrottle]="50" (scrolled)="onScroll()" [scrollWindow]="false"
- style="height: 400px; overflow-y: scroll;">
- <div *ngFor="let item of myPhotosList" class="col-md-4" style="margin-top: 10px;">
- <img style="height: 220px;width: 315px;" src="{{item.url}}" />
- </div>
- </div>
- </div>
- </mat-card>
For that i have provided few properties to an element to work with scrolling.
- infiniteScroll
It is the primary property that defines the content is being scrolled.
- infiniteScrollDistanceUsed to provide distance where we will reach up to the defined percentage of the element, at that time scroll event will be triggered.
- infiniteScrollThrottleNumber of milliseconds after the scroll event will be triggered.
- scrolledIt is a method to perform a specific action when scroll is being reached.
- scrollWindowWe should decide that we want to listen to window scroll event or the element scroll event, here in this demo I have used false because I'm using element to be scrolled.
Open app.component.ts and paste the below code into it.
- import { Component, OnInit } from '@angular/core';
- import { MydataserviceService } from './mydataservice.service';
- import { Photos, PhotosObj } from './_modal';
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.css'],
- providers: [MydataserviceService]
- })
- export class AppComponent implements OnInit {
- title = 'app';
- myPhotosList: Photos[] = [];
- page: number = 1;
- constructor(private service: MydataserviceService) { }
- ngOnInit() {
- // To call api for initial image rendering
- this.getPhotos();
- }
- // To get image data from api
- getPhotos() {
- console.log(this.page);
- this.service.getMyPhotos(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.myPhotosList.push(new PhotosObj(item));
- });
- }
- }
- // When scroll down the screen
- onScroll()
- {
- console.log("Scrolled");
- this.page = this.page + 1;
- this.getPhotos();
- }
- }
No comments:
Post a Comment