What is the best way to keep track of choices made in 'mat-list-option' while using 'cdk-virtual-scroll-viewport'?

I have been working on implementing mat-list-option within cdk-virtual-scroll-viewport in an Angular 14 project. I came across a demo project in Angular 11 that helped me set up this implementation.

In the Angular 11 demo, scrolling functions perfectly and selections of each item persist as expected even after scrolling.

However, when trying to replicate the same functionality in Angular 14, the selection is lost after scrolling, which is not the desired behavior.

Below is a snippet of the HTML template showcasing my implementation. The selectionChange binding manages selections by calling methods such as select and deselect from the SelectionModel found in the corresponding .ts file:

<mat-selection-list (selectionChange)="onSelectionChange($event)">
      <cdk-virtual-scroll-viewport [itemSize]="20" class="example-viewport">
        <mat-list-option
          *cdkVirtualFor="let item of list;"
          [value]="item"
          [selected]="selection.isSelected(item)"
          >{{item}}
        </mat-list-option>
      </cdk-virtual-scroll-viewport>
    </mat-selection-list>

Additionally, the corresponding .ts file contains the SelectionModel, the list array containing dummy items, and the onCheckboxChange method used for the selectionChange output binding:

 selection = new SelectionModel(true);
  list = Array.from(Array(10000).keys());

  onCheckboxChange(selection: MatSelectionListChange) {
    const changedOptions = selection.options;
    for (const option of changedOptions) {
      if (option.selected) {
        this.selection.select(option.value);
      } else {
        this.selection.deselect(option.value);
      }
    }
  }

Despite extensive research and attempts with ChatGPT, I haven't been able to find a solution to make the functionality work seamlessly in an updated Angular version. Would you be able to assist in resolving this issue?

Feel free to explore the Stackblitz examples for both implementations and Angular versions below:

Angular 11 (Demo - Working as Expected): https://stackblitz.com/edit/virtual-scrolling-selection-list-mpawp4?file=src%2Fapp%2Flist-selection-example.html

Angular 14 (Not Functioning Correctly): https://stackblitz.com/edit/angular-b3c9dv-v3pya1?file=src%2Fapp%2Fdatepicker-overview-example.ts

Answer №1

To enhance the speed of rendering, the *cdkVirtualFor function stores previously generated views for later reuse. Instead of creating a new view each time, a cached view is utilized. The size of the cache can be modified using the templateCacheSize property; setting it to 0 disables caching. If your templates consume significant memory, you may want to decrease this value to prevent excessive memory usage.

<mat-selection-list (selectionChange)="onCheckboxChange($event)">
<cdk-virtual-scroll-viewport [itemSize]="48" class="scroll-viewport">
<div *cdkVirtualFor="let item of list;templateCacheSize: 0">
  <mat-list-option      
    [selected]="selection.isSelected(item)"
    [value]="item"
    class="custom-list-option">{{ item }}</mat-list-option>
</div>
</cdk-virtual-scroll-viewport>
</mat-selection-list>

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

Issue with the status of a vue data object within a component

While working on updating my original Vue project, I encountered an error with the data object sports_feeds_boxscores_*. The website features three tabs that display scores for the major sports leagues. I am currently in the process of adding player stats ...

Adding External JS Files to a Node.js Project

I recently discovered how to incorporate a JS file into Node JS. However, I am facing an issue with two JS files in particular - hashing.js and encoding.js. Within encoding.js, I have the following code: exports = exports || {}; exports.encoding = encodi ...

Having trouble declaring custom pipes in Angular

A new pipe named 'shortend.pipe.ts' has been created within the app folder. import { PipeTransform } from "@angular/core"; export class ShortendPipe implements PipeTransform { transform(value: any, ...args: any[]) { return ...

Having trouble transferring information from a form to a page because of the error message " is not defined"?

I'm facing an issue while building a node app. I have set up my routes correctly and installed all the necessary dependencies. However, when I try to load the ("/) "homepage," I receive an error message stating that "newPost" is not defined. Surprisin ...

Azure deployment of a proprietary npm package

As a developer with git integration for my Angular web site, I have successfully checked code into Git and deployed it to Azure. Everything was running smoothly until I encountered an issue when trying to pull a private npm package. It dawned on me that I ...

Angular doesn't support this particular type as an injection token

I'm attempting to create a constructor with a type of string, but I keep encountering the following error: This particular type is not supported as an injection token @Injectable({providedIn: 'root'}) export class DataService { const ...

Is there a way to simplify this "stopwatch" even more?

Looking for advice on simplifying my JS stopwatch timer that currently only activates once and keeps running indefinitely. As a newcomer to JS, this is the best solution I could come up with: let time = 0 let activated = 0 function changePic() { if(a ...

I am able to access the JSON file from the URL without any issues, but for some reason, I am unable to fetch it using $

(function(){ $(document).ready(function(){ $.getJSON('http://dev.markitondemand.com/MODApis/Api/v2/Quote/json?symbol=AAPL&callback=?', function(){console.log("function was run");}); }); }()) I recently delved into working with APIs. Ho ...

The submit form and cordova functions are failing to trigger

I am encountering an issue where I cannot successfully call the submitForm() function when attempting to trigger it via ng-submit. The function does not execute as expected. How can I troubleshoot and resolve this problem? (function () { 'use str ...

React Native: How come my text is breaking like this and failing to adhere to the container's margin settings?

I am facing a challenge in React Native where I need to display multiple elements next to each other, with a flex wrap when there are too many elements or if the text is too long. Each element consists of an icon and text, with the text breaking into the n ...

Trouble encountered while configuring and executing Electron combined with React, Typescript, and Webpack application

I am currently in the process of migrating my Electron application from ES6 to Typescript. Despite successfully building the dll and main configurations, I encounter a SyntaxError (Unexpected token ...) when attempting to run the application. The project c ...

Issue with Mongoose Promise failing to transfer data to the following chain

When querying MongoDB using mongoose with promises, I encounter an issue where the result is only accessible in the initial .then(function(results){ // can send the result from here..}). However, when I manipulate the results and attempt to pass them to th ...

Typescript compiler: Unable to locate the definition for 'Map' data type

I am developing an Electron + Angular application. I have decided to incorporate Typescript for my Electron component, so I created a main.ts file and attempted to compile it to main.js using the 'tsc main.ts' command. Unfortunately, I encountere ...

The page refreshes automatically when the search icon is clicked, but the ajax method does not trigger the page reload

Whenever I click on the search-box <a>, the JavaScript is triggered but doesn't execute the ajax method filter_data_guide_specs(). Instead, the page automatically reloads and fails to read the JS code. HTML <div class="form-group"> < ...

Encountering a timeout error when connecting to MongoDB

Utilizing node.js v12.0.10, I have incorporated MongoDB database to establish a connection and update MongoDB collection with the following connection code: async.parallel({ RE5: function (cb) { MongoClient.connect(config.riskEngineDB ...

Concatenating an unlimited amount of arrays containing Javascript objects

I currently have an array of Groups where each Group contains multiple Users. My goal is to retrieve all the unique Users associated with a given array of Groups. Here is my current approach: let actor = await User.query().findById(req.user.id).eager( ...

"Implementing a button in a flask data table: A step-by-step guide

Hello, I am facing an issue with adding a button to a Bootstrap datatable in Flask (Python) using JavaScript. Any tips or solutions would be greatly appreciated. I am trying to achieve something like this: https://i.sstatic.net/NtaB3.png I have attempted ...

Separate the date format string into tokens

I am currently attempting to create a function that is able to transform a date format string such as %d/%m/%Y %H:%n where the variables are always denoted by a percentage sign followed by one character, into an array of tokens: ["%d", "/", "%m", "/", " ...

Execute and showcase code without redundancies

I have been exploring a way to store JavaScript code within an object and execute specific parts of it upon the user clicking a button. Here's what I've come up with so far: var exampleCode = { test: "$('body').css('background ...

After logging in, the query parameters (specifically code and state) are still present

After logging into my SPA, the query parameters code and state are not removed from the URL. This causes an issue when refreshing the page because the login flow attempts to use the parameters in the URL again. For example, here is the URL after logging in ...