Open In App

Angular PrimeNG Table VirtualScroller Properties

Last Updated : 29 Mar, 2023
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 Angular PrimeNG Properties.

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

Angular PrimeNG VirtualScroller Properties:

  • delay: It is the limit in milliseconds to prevent lazy loading while scrolling. It is of number type and the default value is 250.
  • itemSize: It is the height of a list item. It is of number type and the default value is null.
  • lazy: It determines whether data is loaded and used in a lazy manner. It is of boolean type and the default value is false.
  • scrollHeight: In the inline mode, it is the maximum height of the content area. It is of any type and the default value is null.
  • style: It is the component’s inline style. It is of string type and the default value is null.
  • styleClass: It is the component’s style class. It is of string type and the default value is null.
  • value: It is the object’s array to display. It is of array type and the default value is null.
  • options: It is used to check whether to use the scroller feature. It has ScrollerOptions type and its default value is false.

 

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 Properties using itemSize and scrollHeight.

app.component.html:

HTML




<h1 style="color: green;">GeeksforGeeks</h1>
<h4>Angular PrimeNG VirtualScroller Prepopulated List</h4>
  
<p-virtualScroller [value]="courses" scrollHeight="300px" 
                   [itemSize]="90">
    <ng-template pTemplate="header">
        <div class="flex align-items-center 
             justify-content-center gap-3 flex-wrap">
            List of Courses
            <p-dropdown [options]="listOfOption" 
                 [(ngModel)]="sortingKeyGfg" 
                 placeholder="Sort Courses by: "
                 (onChange)="sortingGeekCourses()" 
                 [style]="{ 'min-width': '10em' }">
            </p-dropdown>
        </div>
    </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">Rs. {{ product.price }}</h6>
                <span [class]="
                    'product-badge status-' + 
                     product.inventoryStatus.toLowerCase()">
                    {{ product.inventoryStatus }}
                </span>
            </div>
        </div>
    </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[];
    sortingKeyGfg: string;
    listOfOption: SelectItem[];
    constructor(private courseService: CourseService) {}
  
    ngOnInit() {
        this.courses = Array.from({ length: 5000 }).map(() =>
            this.courseService.generateCourse()
        );
  
        this.virtualCourses = Array.from({ length: 5000 });
  
        this.listOfOption = [
            { label: "Lowest Price First", value: "price" },
            { label: "Highest Price First", value: "!price" }
        ];
    }
  
    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);
    }
  
    sortingGeekCourses() {
        if (this.sortingKeyGfg.indexOf("!") === 0) this.sort(-1);
        else this.sort(1);
    }
  
    sort(order: number): void {
        let courses = [...this.courses];
        courses.sort((data1, data2) => {
            let value1 = data1.price;
            let value2 = data2.price;
            let result = value1 < value2 ? -1 : value1 > value2 ? 1 : 0;
            return order * result;
    });
    this.courses = courses;
    }
}
  
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 { FormsModule } from '@angular/forms';
import { BrowserAnimationsModule }
    from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { CourseService } from './courseservice';
import { VirtualScrollerModule }
    from 'primeng/virtualscroller';
import { DropdownModule } from 'primeng/dropdown';
  
@NgModule({
    imports: [
        BrowserAnimationsModule,
        VirtualScrollerModule,
        DropdownModule,
        FormsModule,
    ],
    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 the example code that illustrates the use of the Angular PrimeNG VirtualScroller Properties using lazy as true.

app.component.html:

HTML




<h1 style="color: green;">GeeksforGeeks</h1>
<h4>Angular PrimeNG VirtualScroller Properties</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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads