Open In App

Angular PrimeNG Table VirtualScroller Lazy Loading

Improve
Improve
Like Article
Like
Save
Share
Report

Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Angular PrimeNG VirtualScroller Lazy Loading.

VirtualScroller Lazy Loading: By displaying only a small portion of the data in the viewport at any given time, VirtualScroller is an effective method for rendering lists.

Creating Angular application & module installation:

Step 1: Create an Angular application using the following command.

ng new appname

Step 2: After creating your project folder i.e. appname, move to it using the following command.

cd appname

Step 3: Install PrimeNG in your given directory.

npm install primeng --save
npm install primeicons --save

Project Structure: The project structure will look like the following:

 

Steps to run the application: Run the below command to see the output

ng serve --save

Example 1: Below is the example code that illustrates the use of the Angular PrimeNG VirtualScroller Lazy Loading.

  • app.component.html:

HTML




<h1 style="color: green;">GeeksforGeeks</h1>
<h4>Angular PrimeNG VirtualScroller Lazy Loading</h4>
  
<p-virtualScroller
    [value]="virtualCourses"
    scrollHeight="300px"
    [itemSize]="90"
    [lazy]="true"
    (onLazyLoad)="lazyCourse($event)">
      <ng-template let-product pTemplate="item">
        <div class="product-item">
            <div class="product-list-detail">
                <h5 class="mb-2">{{ product.name }}</h5>
                <i class="pi pi-tag product-category-icon"></i>
                <span class="product-category">
                      {{ product.category }}
                  </span>
            </div>
            <div class="product-list-action">
                <h6 class="mb-2">${{ product.price }}</h6>
                <span [class]=
"'product-badge status-' + product.inventoryStatus.toLowerCase()">
                  {{ product.inventoryStatus }}</span>
            </div>
        </div>
    </ng-template>
      
      <ng-template let-product pTemplate="loadingItem">
        <p-skeleton height="90px"
            [style]="{ 'margin-top': '10px' }">
          </p-skeleton>
    </ng-template>
</p-virtualScroller>


  • app.component.ts:

Javascript




import { Component, OnInit } from '@angular/core';
import { CourseService } from './courseservice';
import { LazyLoadEvent, SelectItem } from 'primeng/api';
  
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss'],
})
  
export class AppComponent implements OnInit {
    courses: Course[];
    virtualCourses: Course[];
    constructor(private courseService: CourseService) { }
  
    ngOnInit() {
        this.courses = Array.from({ length: 5000 }).map(() =>
            this.courseService.generateCourse()
        );
        this.virtualCourses = Array.from({ length: 5000 });
    }
  
    lazyCourse(event: LazyLoadEvent) {
        setTimeout(() => {
            let loadedProducts = this.courses.slice(
                event.first,
                event.first + event.rows
            );
            Array.prototype.splice.apply(this.virtualCourses, [
                ...[event.first, event.rows],
                ...loadedProducts,
            ]);
        }, 500);
    }
}
  
export interface Course {
    id?: string;
    name?: string;
    description?: string;
    price?: number;
    quantity?: number;
    inventoryStatus?: string;
    category?: string;
    rating?: number;
}


  • app.module.ts:

Javascript




import { NgModule } from '@angular/core';
import { BrowserAnimationsModule }
    from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { CourseService } from './courseservice';
import { VirtualScrollerModule }
    from 'primeng/virtualscroller';
import { SkeletonModule } from 'primeng/skeleton';
  
@NgModule({
    imports: [
        BrowserAnimationsModule,
        VirtualScrollerModule,
        SkeletonModule,
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [CourseService],
})
  
export class AppModule { }


  • courseservice.ts:

Javascript




import { Injectable } from "@angular/core";
  
export interface Course {
    id?: string;
    name?: string;
    description?: string;
    price?: number;
    quantity?: number;
    inventoryStatus?: string;
    category?: string;
    rating?: number;
}
  
@Injectable()
export class CourseService {
    stockStatus: string[] = ["InStock", "OutOfStock", "StockShortage"];
    courseNames: string[] = [
        "DSA Self Paced",
        "System Design",
        "Operating System",
        "Computer Networks",
        "DBMS",
        "C++ STL",
        "Competitive Coding",
        "DSA Self Paced",
        "System Design",
        "Operating System",
        "Computer Networks",
        "DBMS",
        "C++ STL",
        "Competitive Coding",
        "DSA Self Paced",
        "System Design",
        "Operating System",
        "Computer Networks",
        "DBMS",
        "C++ STL",
        "Competitive Coding",
        "DSA Self Paced",
        "System Design",
        "Operating System",
        "Computer Networks",
        "DBMS",
        "C++ STL",
        "Competitive Coding"
    ];
  
    generateCourse(): Course {
        const course: Course = {
            id: this.gfgId(),
            name: this.gfgName(),
            description: "Course Description",
            price: this.gfgPrice(),
            quantity: this.gfgQuantity(),
            category: "Course Category",
            inventoryStatus: this.gfgStatus(),
            rating: this.gfgRating()
        };
        return course;
    }
  
    gfgId() {
        let myid = "";
        let guess = "ABCDEFRST56789";
  
        for (var i = 0; i < 10; i++) {
            myid += guess.charAt(Math.ceil(Math.random() * guess.length));
        }
        return myid;
    }
  
    gfgName() {
        return this.courseNames[(Math.floor(Math.random() * Math.floor(20)))];
    }
    gfgPrice() {
        return Math.floor(Math.random() * Math.floor(99) + 1);
    }
    gfgQuantity() {
        return Math.floor(Math.random() * Math.floor(85) + 1);
    }
    gfgStatus() {
        return this.stockStatus[(Math.floor(Math.random() * Math.floor(2)))];
    }
    gfgRating() {
        return Math.floor(Math.random() * Math.floor(4) + 1);
    }
}


Output:

 

Example 2: Below is another example code that illustrates the use of Angular PrimeNG VirtualScroller Lazy Loading using the header and footer Templates.

  • app.component.html:

HTML




<h1 style="color: green;">GeeksforGeeks</h1>
<h4>Angular PrimeNG VirtualScroller Lazy Loading</h4>
  
<p-virtualScroller
    [value]="virtualCourses"
    scrollHeight="300px"
    [itemSize]="90"
    [lazy]="true"
    (onLazyLoad)="lazyCourse($event)">
    <ng-template pTemplate="header"
          GeeksforGeeks Courses 
      </ng-template>
        
      <ng-template let-product pTemplate="item">
        <div class="product-item">
            <div class="product-list-detail">
                <h5 class="mb-2">{{ product.name }}</h5>
                <i class="pi pi-tag product-category-icon"></i>
                <span class="product-category">{{ product.category }}</span>
            </div>
            <div class="product-list-action">
                <h6 class="mb-2">${{ product.price }}</h6>
                <span [class]=
"'product-badge status-' + product.inventoryStatus.toLowerCase()">
                  {{ product.inventoryStatus }}</span>
            </div>
        </div>
    </ng-template>
      
      <ng-template let-product pTemplate="loadingItem">
        <p-skeleton height="90px"
            [style]="{ 'margin-top': '10px' }">
          </p-skeleton>
    </ng-template>
    
    <ng-template pTemplate="footer"
          Copyright@GeeksforGeeks 
      </ng-template>
</p-virtualScroller>


  • app.component.ts:

Javascript




import { Component, OnInit } from '@angular/core';
import { CourseService } from './courseservice';
import { LazyLoadEvent, SelectItem } from 'primeng/api';
  
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss'],
})
  
export class AppComponent implements OnInit {
    courses: Course[];
    virtualCourses: Course[];
    constructor(private courseService: CourseService) {}
  
    ngOnInit() {
        this.courses = Array.from({ length: 5000 }).map(() =>
            this.courseService.generateCourse()
        );
        this.virtualCourses = Array.from({ length: 5000 });
    }
  
    lazyCourse(event: LazyLoadEvent) {
        setTimeout(() => {
            let loadedProducts = this.courses.slice(
                event.first,
                event.first + event.rows
          );
          Array.prototype.splice.apply(this.virtualCourses, [
              ...[event.first, event.rows],
              ...loadedProducts,
          ]);
        },500);
    }
}
  
export interface Course {
    id?:string;
    name?:string;
    description?:string;
    price?:number;
    quantity?:number;
    inventoryStatus?:string;
    category?:string;
    rating?:number;
}


  • app.module.ts:

Javascript




import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } 
    from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { CourseService } from './courseservice';
import { VirtualScrollerModule } 
    from 'primeng/virtualscroller';
import { SkeletonModule } from 'primeng/skeleton';
  
@NgModule({
    imports: [
        BrowserAnimationsModule,
        VirtualScrollerModule,
        SkeletonModule,
    ],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [CourseService],
})
  
export class AppModule {}


  • courseservice.ts:

Javascript




import { Injectable } from "@angular/core";
  
export interface Course {
    id?: string;
    name?: string;
    description?: string;
    price?: number;
    quantity?: number;
    inventoryStatus?: string;
    category?: string;
    rating?: number;
}
  
@Injectable()
export class CourseService {
    stockStatus: string[] = ["InStock", "OutOfStock", "StockShortage"];
    courseNames: string[] = [
        "DSA Self Paced",
        "System Design",
        "Operating System",
        "Computer Networks",
        "DBMS",
        "C++ STL",
        "Competitive Coding",
        "DSA Self Paced",
        "System Design",
        "Operating System",
        "Computer Networks",
        "DBMS",
        "C++ STL",
        "Competitive Coding",
        "DSA Self Paced",
        "System Design",
        "Operating System",
        "Computer Networks",
        "DBMS",
        "C++ STL",
        "Competitive Coding",
        "DSA Self Paced",
        "System Design",
        "Operating System",
        "Computer Networks",
        "DBMS",
        "C++ STL",
        "Competitive Coding"
    ];
  
    generateCourse(): Course {
        const course: Course = {
            id: this.gfgId(),
            name: this.gfgName(),
            description: "Course Description",
            price: this.gfgPrice(),
            quantity: this.gfgQuantity(),
            category: "Course Category",
            inventoryStatus: this.gfgStatus(),
            rating: this.gfgRating()
        };
        return course;
    }
  
    gfgId() {
        let myid = "";
        let guess = "ABCDEFRST56789";
  
        for (var i = 0; i < 10; i++) {
            myid += guess.charAt(Math.ceil(Math.random() * guess.length));
        }
        return myid;
    }
  
    gfgName() {
        return this.courseNames[(Math.floor(Math.random() * Math.floor(20)))];
    }
    gfgPrice() {
        return Math.floor(Math.random() * Math.floor(99) + 1);
    }
    gfgQuantity() {
        return Math.floor(Math.random() * Math.floor(85) + 1);
    }
    gfgStatus() {
        return this.stockStatus[(Math.floor(Math.random() * Math.floor(2)))];
    }
    gfgRating() {
        return Math.floor(Math.random() * Math.floor(4) + 1);
    }
}


Output:

 

Reference: https://primefaces.org/primeng/virtualscroller



Last Updated : 29 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads