Angular 2's Superior Array Change Detection

My project includes a component hierarchy structured like this:

@Component({
...
})
export class A {

  constructor(private _serviceThatDeliversData: Service){} 

  getData(): Array<DataItem> {
    return this._serviceThatDeliversData.getData();
  }
}

html:

<b-selector [data]="getData()"></b-selector>

Child component:

@Component({
  selector: 'b-selector'
  ...
})
export class B {
  @Input() data: Array<DataItem>;
}

html:

<ul>
  <li *ngFor="let item of data">
    <c-selector [item]="item"></c-selector>
  </li>
</ul>

In my application, the parent component 'A' retrieves data from a service called serviceThatDeliversData. This service generates a list of DataItems every time it receives data from a websocket. The list is then passed down to child component 'B', where each list entry serves as a basis for subcomponents ('C').

The issue I am facing is that whenever the service updates the list, all C components along with B are recreated. It seems like Angular treats the updated list as entirely new entries, even if only one item has been added or removed, or if a field within an item has changed.

This restart causes any ongoing animations in the view of C components to stop and start again when the list is recreated. This interruption, along with other side effects, needs to be avoided.

Would it be possible for Angular to update only those C components related to a DataItem that has internally changed, as well as those that have been added or removed from the list? Is there a way to leave unchanged components untouched?

I have researched using changeDetection: ChangeDetectionStrategy.OnPush but haven't found a suitable example that addresses my specific problem of dealing with changing arrays and elements within them.

One potential solution could involve storing a copy of the list in 'B', manually checking for changes, and reacting accordingly—potentially including an animation to indicate additions or removals. However, this approach would require preventing Angular from updating (recreating) 'B' and 'C' components altogether. Perhaps utilizing the same array by clearing it and repopulating it with new entries might offer a workaround.

Nevertheless, I am curious to know if there exists a raw Angular mechanism that could achieve this goal.

Answer â„–1

The update detection method OnPush specifically detects changes to values marked with the Input decorator, only if the reference of the value changes.

For instance, when doing myArray[1] = 'a';, it only modifies the array without creating a new reference. Therefore, Angular using the OnPush strategy will not detect this change. You need to clone the array and make the modification in order to create a new array reference.

If you are facing issues with Angular recreating elements within an ngForOf directive, I have addressed it in another response. Please refer to the note at the end of that response.

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

Setting up Angular asset URL dynamically

Hey there, I'm currently working with Angular 7 and running into an issue with the production build of my application. The application is located in a subfolder on the server at www.hshsh.com/cm/, where 'cm' is the subfolder that houses the ...

Resize the p-accordion within a p-splitter using PrimeNG programmatically

Please find the code for my component below: In this component, I have a p-splitter that is divided into 3 sections. Each section contains a p-accordion, which in turn includes a p-table. <div class="card w-full"> <p-splitter [p ...

Create a variable to serve as a key within an Array

Encountering an issue with initializing an array while using the ngx-gauge library to display gauges in my application. One of the attributes is thresholds, which determines three different colors based on the value. For example: thresholds = {'0&apos ...

Checking for palindromes in a 2D array

I am currently working on a task to determine if a 2D array is a palindrome both row-wise and column-wise using a String or Character variable. I am a bit confused as we are only covering 2D arrays and loops in our lesson, and I keep coming across referenc ...

Learn how to efficiently compare an array of objects in Angular 8 by leveraging reactive forms

After utilizing reactive forms, I encountered an issue where the values were being assigned to the HTML due to an array of objects in the reactive form. This led me to implement a method for comparing objects with the existing object whenever any action is ...

Efficiently import all files within a folder using TypeScript

While working with NodeJS and TypeScript, the process of requiring files is slightly different. Check out the example below: const fs = require('fs') fs.readDirSync('/dir/name') .forEach(dir => require(dir)) How can I achieve the s ...

Error in outputting JSON string due to multilevel PHP array structure

I'm trying to create a multilevel PHP Array using a DB connection that can be encoded in JSON. The issue is that there is an extra pair of square brackets in the output that I want to eliminate. Here's the PHP code I have: ## Step 1 ########### ...

Unable to update state in my React app when clicking on a button

There is a requirement for a button click to filter the job-card array by one specific category. For example, clicking on the button "Marketing" should only show jobs from the array that have the property "jobstags: Marketing". I followed a similar procedu ...

TypeScript does not accept union types in compatible overloads

When it comes to the Date object, you can create an instance using either a number or a string: new Date("..."); new Date(123456); Interestingly, while both number and string types are accepted, the union type string|number is not: if (typeof value === ...

Does numpy.multiply always have the same outcome as the * operator?

According to the numpy.multiply documentation: The numpy.multiply function is equivalent to x1 * x2 in terms of array broadcasting. Is there a difference between np.multiply(x1, x2) and x1 * x2 in any scenario? Where can I find the implementation deta ...

cutting into a 2-dimensional numpy array

Here is the code snippet in question: import numpy as np my_array = [[0, 1], [0, 6], [0, 1], [0, 6], [0, 1], [0, 6], [0, 1], [0, 6], [0, 1], [0, 6], [0, 1], [0, 6], [0, 1], [0, 6], [0, 1], [0, 6], [0, 1], [0, 6]] copy = np.array(my_array) np.mean(copy)[:,1 ...

Exceeding the bounds of the array

Is there a way to detect and prevent accessing character arrays beyond their limits in C++? For example, if I have two character arrays of size 100 each (char array1[100], char array2[100]), how can I ensure that no one is trying to access memory beyond th ...

Tips for displaying error messages on forms in Ionic 2

I have successfully tested the following code in my browser. Here is the snippet from my .html file <ion-item> <ion-label primary floating>FIRST NAME</ion-label> <ion-input type="text" id="firstname" class="form-control" formC ...

What steps can be taken to access our Angular application via URL after deploying it on the Azure cloud platform?

My Angular app has been successfully deployed on Azure and is currently running. However, I am unsure of how to access it through my browser. The application is running on the default port 4200. Can anyone provide guidance on any necessary configurations ...

Eliminating tail recursion for conditional types is ineffective

In TypeScript version 4.5, the feature of tail call optimization was introduced for recursive generics. The code snippet below calculates Fibonacci numbers (in unary) up to F12, but encounters an error when trying to compute F13 due to the "Type instantiat ...

Tips for targeting a specific element with providers in Ionic

By using the specified pattern, I am aiming to achieve a unique toolbar or header for only certain pages. Is there a way to accomplish this without injecting the provider and keeping the page as a standalone? My understanding of Ionic is still developing, ...

What is the reason behind Prettier's decision to eliminate brackets in TypeScript formatting

When I format TypeScript files using Prettier, it consistently removes the brackets as shown in the following scenario: private requestFilterHooks: Dict<(...args: any[]) => (Promise<void> | void)> = {}; This code snippet will be converted t ...

Error Message in Terminal When Launching React Application Using Webpack

I am encountering several errors in the node terminal while attempting to launch my react-app [at-loader] ./node_modules/@types/webpack/index.d.ts:23:16 TS2665: The module name in augmentation is invalid. Module 'webpack/lib/dependencies/HarmonyE ...

What is the most effective method for converting a dynamic list of arguments into a byte array in C++?

In my C implementation, I have a function that serializes a variable list of arguments into a byte array, allowing me to save multiple variables into a file. The C code for this serialization process is as follows: static uint8_t byte_array[1024]; /* As ...

Create a standalone 404 page using React Router that is completely isolated from any other components

Currently, I am collaborating with <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfadbabebcabbaadf2adb0aaabbaadf2bbb0b29fe9f1ebf1ed">[email protected]</a> and the code I am working on looks like this: index.tsx ...