I am trying to implement an infinite scroll using cdk-virtual-scroll-viewport where I load images lazily as the viewport reaches the bottom of the page into a grid.
Problem is that it only renders 3 rows and when I reach the bottom although new images are retrieved but it does not show in the browser.
Here is the html code where I use mat-grid-list for each row:
<cdk-virtual-scroll-viewport appendOnly [itemSize]="itemSize" class="grid-viewport" (scrolledIndexChange)="viewPortChange($event)">
<mat-grid-list *cdkVirtualFor="let item of items" [cols]="gridColumns" gutterSize="10px" class="grid-list">
@for(it of item; track it.description){
<mat-grid-tile class="grid-item">
<img [src]="it.imageUrl" alt="Item image" class="grid-img">
</mat-grid-tile>
}
</mat-grid-list>
</cdk-virtual-scroll-viewport>
Following is the component typescript code where viewPortChange method is called when bottom of the page is reached but the new images are not shown in the browser. I store the data as a nested array where the inner arrays contain 4 images each:
items : any[][] = [];
loadedElementsCount: number = 0;
batchSize: number = 12;
itemSize: number = 200;
gridColumns: number = 4;
nbLoadRows = 3;
constructor() {}
ngOnInit() {
this.calculateGridSettings();
this.loadMoreItems();
}
loadMoreItems() {
const newItems = Array.from({ length: this.batchSize }, (_, i) => this.createItem(i + this.items.length*this.gridColumns));
for(let i = 0; i < this.batchSize; i+=this.gridColumns){
this.items.push(newItems.slice(i,i+this.gridColumns));
}
//this.items = [...this.items, ...newItems];
this.loadedElementsCount += this.batchSize;
console.log("loaded number");
console.log(this.loadedElementsCount);
//console.log(newItems);
console.log(this.items);
}
viewPortChange(event: any){
console.log("evemtdtsr number");
console.log(event)
if((event+1)*this.gridColumns >= this.loadedElementsCount){ //*this.gridColumns
this.loadMoreItems();
}
}
createItem(index: number) {
return {
imageUrl: `https://picsum.photos/200/300?random=${index}`,
description: `Item ${index}`
};
}
Anyone has an idea why this happens?