Update the specific component according to the identified modifications

In my project, I have two simple components: parent and child. The parent component contains an Array and for each element in the array, it renders the child component.

parent.component.ts

export class parent implements OnInit {

  data: CustomType[] = [
     {
       id: "child1",
       records: [] // array of string
     },
     {
       id: "child2",
       records: [] // array of string
     }
  ];

  ngOnInit() {}
}

parent.component.html

<section>
  <ChildComponent *ngFor="let child of data | async" [obj]="child"/>
</section>

child.component.ts

export class child implements OnInit {

  // Data is passed from the parent component
  @Input() obj: CustomType;

  ngOnInit() {}
}

child.component.html

<div>
  {{ obj.id }}
</div>

The Issue

While the current code is functional, the problem arises when the records of an element in the array change, causing all child components to re-render. I am seeking a solution to re-render only the specific component that has changed.

I am exploring the use of onPush Change Detection in this scenario.

For Instance:

If data[0].records is altered, only the child component corresponding to data[0] should re-render.

Answer №1

Implementing the trackBy function allows for more efficient rendering by only updating the specific element that has changed!

html file

<section>
  <ChildComponent *ngFor="let child of data | async; trackBy: trackBy" [obj]="child"/>
</section>

ts file

  trackBy(index, item) {
    return item.id;
  }

For more information, check out the source

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

While running tslint in an angular unit test, an error was encountered stating 'unused expression, expected an assignment or function call'

Is there a method to resolve this issue without needing to insert an ignore directive in the file? Error encountered during command execution: ./node_modules/tslint/bin/tslint -p src/tsconfig.json --type-check src/app/app.component.spec.ts [21, 5]: unuse ...

Using Firebase callable functions with React Native

Can I use Firebase callable functions with React Native? I have successfully deployed an onCall function and it is visible in my dashboard. I have initialized the functions using: // Initialize Cloud Functions through Firebase firebase.functions(); The ...

Making a request using AJAX to retrieve data from an API

Looking to create an API GET request using ajax? Want a jquery function that takes an api key from the first input field and displays a concatenated result on the second input field (#2)? The goal is to make the get request to the value shown in the 2nd ...

Automated Form Submission: A Guide to Automatically Sending the Form After Captcha Verification

I'm looking to incorporate ReCaptcha into my website in order to display additional data. My goal is to have the form automatically submitted once the ReCaptcha has been completed, eliminating the need for an extra submit button. However, I've en ...

Having trouble importing a TypeScript file from the node_modules directory in Angular 2

Incorporating Google Map places into my Angular 2 project has been a challenge. npm install angular2-google-map-auto-complete https://i.sstatic.net/Vwi5h.png An error is occurring as the module cannot be found: https://i.sstatic.net/jVonb.png Could so ...

Centralize Your 3D Model with Three.js

Hello everyone, this is my first time posting on stackoverflow. For the past few days, I've been struggling to use the Three.js library (specifically version number r99). I managed to load a 3D model successfully, but it appears behind and not centere ...

How about: "Add random HTML content using jQuery each time the page is refreshed

Currently facing this issue: I implemented a jquery plugin fullPage.js by Alvaro Trigo on my website. The plugin script automatically inserts the html structure in certain elements... in my html I have: <div class="section fp-auto-height-responsive" ...

Transforming the DOM using jQuery

I am looking to manipulate the DOM using jQuery. This is the initial source code: <td class="name"><a href="position_details.php?x=-109&amp;y=95">21</a> </td> <td class="name"><a href="position_details.php?x=-109& ...

Is it possible for the Observable call in Angular 4 to function similarly to jQuery's synchronous AJAX method?

As I have a business logic function that needs to use HttpGet and I must wait for the result before continuing, jQuery's ajax can handle this easily. But I am curious if Observables have a similar feature? I was hoping for the result to be: John An ...

The ideal way to efficiently await retrieved data in vue.js to ensure smooth integration in another function

Is there a way to properly handle the successful fetch event before executing the loadMarkers() method? I keep encountering an error because monitorsData.monitors is undefined. I attempted using await with fetch but I'm unsure of the correct usage. ...

PHP encountering a bad escaped character while parsing JSON using JSON.parse

I'm encountering an issue with JSON parsing. In my PHP code, I have the following: json_encode(getTeams(),JSON_HEX_APOS); This returns a large amount of data. Sample data: To provide more clarity, let's assume I have this: my_encoded_data ...

What is the best way to initialize firebase with context in a React application?

Currently, I'm following a tutorial at this link: I've hit a roadblock at the following step: Context.jsx import React from 'react'; const FirebaseContext = React.createContext(null); export default FirebaseContext; index.js impo ...

The art of expanding Angular's HTTP client functionality

I understand that the following code is not valid in Angular, but I am using it for visual demonstration purposes. My goal is to enhance the Angular HTTP client by adding custom headers. I envision creating a class like this, where I extend the Angular h ...

javascript send variable as a style parameter

screen_w = window.innerWidth; screen_h = window.innerHeight; I am trying to retrieve the dimensions of the window and store them in variables. Is there a way to then use these variables in my CSS styles? For example: img { width: screen_w; height: s ...

Adjusting the alignment of the horizontal bars in react-chartjs-2

I have configured the graph with the following settings: { type: 'horizontalBar', indexAxis: 'y', barThickness: 12, scales: { x: { suggestedMax: 6, suggestedMin: 0, grid: { display ...

Is it possible to preserve the query parameters from the previous page using Vue Router's Navigation guard feature?

Hey there! So, I'm looking to pass a query from the current page to the next one without manually coding it into all of my push functions. I was wondering if there's a way to do this through Navigation guard or some hooks? I did some research an ...

Retrieve the id of the clicked hyperlink and then send it to JQuery

<a class = "link" href="#" id = "one"> <div class="hidden_content" id = "secret_one" style = "display: none;"> <p>This information is confidential</p> </div> <a class = "link" href="#" id = "two" style = "display: non ...

Communication with child processes in node.js is not done using the child_process module

Hello Everyone, I'm currently experimenting with node.js to utilize JS plugins developed by others using the child_process API. However, I'm facing an issue where the child process is not able to communicate effectively with the parent process. ...

Retrieving updated data from a service does not trigger a refresh of the view

Having an issue with rendering data obtained from a service. Here is the situation: The service retrieves values from a distant API using an Observable: @Injectable() export class myService { constructor(private http: Http) { } getData(listLength: num ...

Update the header background color of an AG-Grid when the grid is ready using TypeScript

Currently working with Angular 6. I have integrated ag-grid into a component and I am looking to modify the background color of the grid header using component CSS or through gridready columnapi/rowapi. I want to avoid inheriting and creating a custom He ...