Introducing the powerful combination of PrimeNG's V18 Virtual Scroller and Angular 18's @if

Recently, I encountered a challenge while using the @for loop to iterate through my dataset and repeat the same structure of elements. Due to the increasing size of the dataset, I decided to integrate the VirtualScroller component provided by PrimeNG.

To my surprise, the VirtualScroller component failed to render properly and displayed a blank screen. After carefully inspecting my code line by line, I discovered that the issue arose when using the @if syntax within the template section. Interestingly, there were no error messages to indicate what went wrong.

In an attempt to seek assistance from the community, I have replicated the problem on stackblitz. It appears that the problem lies within the virtualscroller component of PrimeNG. I am reaching out to inquire whether it's acceptable to utilize such syntax within a template or if I am implementing it incorrectly.

I would greatly appreciate any insights or suggestions!

Below is a snippet of the code:

<div class="card flex justify-center">
  <p-virtualscroller
    [items]="items"
    [itemSize]="50"
    scrollHeight="200px"
    styleClass="border border-surface"
    [style]="{ width: '200px', height: '200px' }"
  >
    <ng-template pTemplate="item" let-item let-options="options">
      <div
        class="flex items-center p-2"
        [ngClass]="{ 'bg-surface-100 dark:bg-surface-700': options.odd }"
        style="height: 50px"
      >
        @if(truthy) { {{ item }} }
      </div>
    </ng-template>
  </p-virtualscroller>
</div>
@Component({
  selector: 'panel-basic-demo',
  templateUrl: './panel-basic-demo.html',
  standalone: true,
  imports: [ImportsModule],
})
export class PanelBasicDemo {
  selectedPreset: string = 'aura';

  items!: string[];

  truthy: boolean = true

  constructor(private config: PrimeNGConfig) {
    this.config.theme.set({ preset: Aura });

    this.items = Array.from({ length: 1000 }).map((_, i) => `Item #${i}`);
  }
}

Answer №1

Based on my assessment, it appears that:

The component properties are not visible within the ng-template due to rendering inside primeng virtual scroll. To address this, attach the variable to the data array for accessibility.

However, there seems to be a bug in primeng related to change detection, particularly affecting @if and *ngIf. It is recommended to report this issue on their GitHub repository. Additionally, note that the virtual scroll documentation API page may not be displaying correctly.

Error: [email protected]:26 ERROR RuntimeError: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '[object Object]'. Current value: 'undefined'. Expression location: Scroller component. Find more at

In the meantime, you can temporarily hide elements using the [hidden] attribute.

<div class="card flex justify-center">
  <p-virtualscroller
    [items]="items"
    [itemSize]="50"
    scrollHeight="200px"
    styleClass="border border-surface"
    [style]="{ width: '200px', height: '200px' }"
  >
    <ng-template pTemplate="item" let-item let-options="options">
      <div
        class="flex items-center p-2"
        [ngClass]="{ 'bg-surface-100 dark:bg-surface-700': options.odd }"
        style="height: 50px"
      >
        <span [hidden]="!item.truthy"> {{ item.label }} </span>
      </div>
    </ng-template>
  </p-virtualscroller>
</div>

Stackblitz Demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The element 'PROGRAM_ID' is not recognized within the 'import @metaplex-foundation/mpl-token-metadata' type

I am currently in the process of creating a token within the Solana network, but I've encountered a particular issue. I have successfully installed @metaplex-foundation/mpl-token-metadata and integrated it into my code; however, an error is persisting ...

What could have caused this issue to appear when I tried running ng build --prod?

Issue encountered while trying to build the ng2-pdf-viewer module: An error occurred in the webpack loader (from @angular-devkit/build-optimizer) with the message: TypeError: Cannot read property 'kind' of undefined. This error is related to A ...

Using Private and Protected Methods in Typescript with React: Best Practices

Currently, I am engrossed in developing a React application utilizing Typescript. In cases where a component needs to offer functionality through a reference, I typically incorporate a public method (public focus() : void {...}). However, I find myself pon ...

Understanding how to handle prop types in a React application using Typescript

My current task involves using the react-google-maps library to integrate Google Maps API into my project. The documentation specifies a certain way to set up the maps component: const GoogleMapComponent: React.ComponentClass<{}> = compose( with ...

Traversing through an Array of Objects in Angular 4

I need to loop through an array object within the subscribe test.ts file export class AppComponent implements OnInit { title = 'app works!'; observableBooks: Observable<Book[]> books: Book[]; newarray: any[]; ...

If a radio button is selected, direct the user to a different webpage based on

**I have 2 radio buttons(button 1, button 2), when I select button 1 and click on the next button it redirects to another page. Similarly, when I select button 2 and click on the next button, it also redirects to another page. How is this *possible. <d ...

The error in the Angular CLI build is caused by a permission issue when attempting to create the directory `/opt/build`. But why is the directory `opt/build` being created and how can this be modified?

Running the ng build command in the node 14.15.5 docker image results in an error message: ./node_modules/google-protobuf/google-protobuf.js - Error: Module build failed (from ./node_modules/@angular-devkit/build-angular/src/babel/webpack-loader.js): Error ...

Challenges in Angular 2

After building an application using Angular 2 with Lite Server, I noticed that it initially runs smoothly and quickly. However, over time, the performance starts to degrade and my application becomes sluggish. To address this issue, I typically restart L ...

Animating the height of a container seamlessly in a crossfade animation

I'm struggling to achieve the desired effect with Angular animations. The typical crossfade works well for opacities, but the height is not being animated as expected. Can anyone help me figure out what I'm doing wrong? animations: [ trig ...

Setting up AWS Amplify for an AppSync subscription WebSocket endpoint: Step-by-step guide

Is there a way to specify a websocket endpoint with Amplify.configure(awsConfig)? The documentation only covers how to set up a singular http endpoint using the aws_appsync_graphqlEndpoint For more information, you can refer to the AWS Amplify.configure d ...

execute the function once the filereader has completed reading the files

submitTCtoDB(updateTagForm:any){ for(let i=0;i<this.selectedFileList.length;i++){ let file=this.selectedFileList[i]; this.readFile(file, function(selectedFileList) { this.submitTC(updateTagForm,selectedFileList); }); } } } ...

What are the specified actions with Angular and p-picklist?

I have a situation with my angular code where I am displaying 2 lists and allowing items to be moved between them. I am looking for a way to trigger a method only when an item is moved from the available list to the selected list. I attempted to use (cli ...

Utilizing generic functions as arguments in other functions

Imagine if I were to create a type called CoolType in this manner: type CoolType<T> = {message: string, result: T} Next, let's define a type called CoolFunction which represents a function that returns CoolType: type CoolFunction = <T>( ...

Angular NgClass Issue (Unable to bind to 'ngClass' as it is not recognized as a property of 'a')

Hi there! I am relatively new to using Angular and I am currently facing an issue while attempting to dynamically add a Bootstrap class to my HTML based on the active tab. Unfortunately, I am encountering an error. Can anyone provide assistance? The error ...

Develop an all-encompassing Ui-lib for NX or design a separate library for each unique Ui use

Looking to incorporate shared libraries into my Angular project, I've outlined two different approaches below. While both are effective, I'm unsure which one is the optimal choice for implementation. #1: Single UI Library with Multiple Components ...

Transform an array containing individual objects into an object consisting of arrays while ensuring comprehensive Typings

JavaScript often deals with converting an array of objects into an object of arrays, but how would you accomplish this in TypeScript while maintaining full typing support? ...

The discovery document is expecting the issuer to be angular-oauth2-oidc in Azure B2C, but the issuer is

During the development of my Angular2 App, I encountered an issue while attempting to implement authentication using a B2C Tenant. Unfortunately, I am receiving the following error: Invalid issuer in discovery document expected: I have followed the setup ...

Confirm that the array includes all unique objects that have the specified properties and values

I have been searching through the class-validators samples and documentation, but I have not been able to find the specific validation that I require. Within my code, I have an array of object literals that each contain unique properties and values. const ...

The console displays 'undefined' when ngOninit is called, but it successfully returns data when the function

Having an issue where I need to display the data stored in the userData variable, but when using console.log(), it only shows "undefined". However, if I place the console log inside a function and trigger it with a button click, the actual data is display ...

Unable to navigate using react-router after logging out without a page refresh

In my logout approach, everything seems to work fine - there are no errors in the console, localHistory is cleared successfully, but for some reason it cannot navigate to the login page without refreshing the current page. const handleLogout = () => { ...