Encountering an issue with Angular virtual scrolling: ViewDestroyedError arises when trying to utilize a destroyed view during detectChanges operation

My implementation involves using virtual scrolling from the cdk within a trigger-opening sidenav on a mat-radio element. Here is the code snippet:

ts -

...
@Component({
  selector: 'app-generic-options-list',
  templateUrl: './generic-options-list.component.html',
  styleUrls: ['./generic-options-list.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class GenericOptionsListComponent implements OnInit, OnChanges {
  @Input() options: MultiSelectOption[];

  _options: MultiSelectOption[];
...
 ngOnInit(): void {
    this.refreshOptions();
  }

private refreshOptions() {
    this._options = this.options;
...
}

template -

<cdk-virtual-scroll-viewport itemSize="30" class="scroll-viewport" *ngIf="type === 'single'">
<mat-radio-group >
    <mat-radio-button 
    *ngFor="let option of selected"
    [value]="option"
    [checked]="true"
    (click)="onRadioOptionClick(option)">
  {{option.val}}
</mat-radio-button>
  <mat-radio-button 
  *cdkVirtualFor="let option of _options"
      [value]="option"
      [checked]="false"
      (click)="onRadioOptionClick(option)"
      class="scroll-item"
      >
    {{option.val}}
  </mat-radio-button>
</mat-radio-group>
</cdk-virtual-scroll-viewport>

and includes appropriate CSS styling.

Whenever the above component disappears from the parent component for a known reason but doesn't activate the onDestroy method, I encounter an error causing the sidenav to get stuck and other unexpected behaviors. Despite attempting to use onPush as a solution, it did not resolve the issue. What would be the correct approach to fix this problem?

Answer №1

To implement virtual scrolling in your .html file, use the following code:

<cdk-virtual-scroll-viewport itemSize="50" class="example-container">
  <div *cdkVirtualFor="let item of items" class="example-item">{{item}}</div>
</cdk-virtual-scroll-viewport>

In your .ts file, include the below TypeScript code:

import {ChangeDetectionStrategy, Component} from '@angular/core';

/** @title Basic virtual scroll */
@Component({
  selector: 'virtual-scroll-example',
  styleUrls: ['virtual-scroll-example.css'],
  templateUrl: 'virtual-scroll-example.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class VirtualScrollExample {
  items = Array.from({length: 100000}).map((_, i) => `Item #${i}`);
}

If needed, add custom CSS styles to your .css file as follows:

.example-container {
  height: 200px;
  width: 200px;
  border: 1px solid black;
}

.example-item {
  height: 50px;
}

Ensure you follow these steps to enable virtual scrolling functionality.

Answer №2

The issue has been resolved thanks to the Angular team. It turns out my cdk was outdated, but updating it fixed the problem completely.

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

What is the most streamlined way to send data from HTML forms using solely JavaScript?

I currently employ jQuery to transmit data from my HTML forms and then I utilize PHP to save it in my database. Below is the code snippet that I am using: HTML FORM: <form id="formpost" action="" method="post" onsubmit="return false"> <input t ...

"Utilizing a background image within a component to completely cover the entirety

Hey everyone, I need some help with a confusing issue. I'm currently working on an AngularJs project and I am struggling to set a background image for a specific component without affecting the entire application. My goal is to have the image cover t ...

Using Google Cloud Function to write and read a JSON file

I'm currently tackling a project that involves comparing two JSON files fetched at different time intervals. Essentially, it's a continuous cron job that retrieves a new JSON response from an API every 20 seconds and compares it with the previous ...

Using the <script> attribute within the <head> tag without the async or defer attributes

https://i.stack.imgur.com/cRFaR.pngCurious about Reddit's use of the async or defer attribute in the script tag. Are there situations where blocking the parser is necessary? ...

Bring in an Angular Component into a different Component by stating the name of the component as an input parameter

In my project, I am looking to develop an angle component made up of multiple sub-components. The end goal is to construct a versatile tree component with nodes that cater to different data types. Each data type in the tree component will import specific s ...

Angular 2: Emptying input field value on click event

I am experiencing an issue with resetting my input values. I have a search bar with filter functions. When I enter a value, it displays a list below and I want to add a function to these links. When I click on one of them, it takes me to another component ...

The Problem of Unspecified Return Type in Vue 3 Functions Using Typescript

Here is the code snippet I am working with: <template> <div> <ul v-if="list.length !== 0"> {{ list }} </ul> </div> </template> < ...

Manipulating the InnerHTML content of a total of 144 individual cells

I am currently developing a tile-based game using tables. Each td cell contains the following code: <td> <div id="image" style="display:none; display: fixed; right: 5; top:2;"><img src="http://thumb7.shutterstock.com/display_pic_with_logo ...

Invoking Ajax Within Every Loop

I am creating dynamic HTML buttons where, upon pressing each button, I want to make an AJAX call to retrieve a value. However, I am encountering an issue where I get as many console outputs as the number of buttons pressed. Here is my PHP code: if(isset($ ...

What is the process for accessing npm packages through a website?

Recently, I've been delving into the realm of Node.js and attempting to configure a specific Node.js package created by Uber. Despite my limited experience with Node.js, I rigorously followed these steps: Initiated cloning their repository from here ...

Exploring the intricacies of React's useEffect: Solving the challenge of updating data when two separate dependency arrays are

I am facing an issue with two different useEffect hooks where the dependency arrays are different. const [dateFilterSort, setDateFilterSort] = useState({ queryText: initialQueryText(params.sortName), cardText: initialCardText(params.sortName), ...

What does the error message "unsupported command-line flag" in Chrome mean for Protractor?

Recently jumping on the Protractor bandwagon, I found myself facing an issue while running my tests on Chrome (an error message appears below the address bar in the browser): A worrisome warning popped up saying something about '--ignore-certificat ...

Trigger a callback in ASP.NET's CallbackPanel using JavaScript every 10 seconds

I am attempting to automatically trigger the callback of a CallbackPanel using JavaScript in my WebFormUserControl every 10 seconds. While I can trigger it with an ASPxButton and ClientSideEvents, my ultimate aim is to have it start automatically every 10 ...

Avoiding the use of apostrophes in jQuery or JavaScript

I need to show the text below for the <span> element. What's the best way to handle single quotes in this case? $("#spn_err").text($('#txt1').attr('value')+" is not valid"); The desired message format is 'ZZZ' is ...

The absence of AudioPlayer may be responsible for the compilation failure on Vercel

Here is the latest code snippet import { useState, useEffect, useRef } from "react"; import { FaPlay, FaPause, FaForward, FaBackward } from "react-icons/fa"; export default function Player() { const [isPlaying, setIsPlaying] = useState(false); const [ ...

Using jQuery.ajax and not retrieved using a GET request

I'm attempting to extract the value (adults) from a select option field using a GET request with AJAX. I am able to extract the value from the URL by displaying an alert with the URL in the jQuery function. However, I am unable to retrieve the value w ...

Implementing unique union type in React: Effective ways to declare typescript type for prop value

I am currently facing an issue where I need to set a specific type for a prop value. However, the challenge lies in the fact that the types are string unions which can vary depending on the usage of the React Component. Let me provide you with the TypeScr ...

Utilizing Rails to incorporate a comment box through jquery on individual posts within a index page showcasing all listed posts

As I display a list of posts on my index file, I want each post to have its own comments section. To achieve this, I have added a "Show Comments" button for each post. However, when I click the button, jQuery triggers all comment boxes on the page instead ...

The Issue of Anti Forgery Token Not Functioning Properly with Ajax JSON.stringify Post

I have been attempting to utilize an Anti Forgery token with JSON.stringify, but despite researching multiple sources, I have not been successful. Below is my AJAX code for deleting some information without any issues. Upon adding the anti forgery token, I ...

Implement a jQuery loop that utilizes the fadeIn effect

Currently, I have a basic jQuery function in place to generate a small image slider: function gridhover() { $(".grid-item .slide-image").each(function(index) { $(this).delay(400*index).fadeIn(300); }); } $( ".grid-item" ).hover(function() ...