The child component is failing to detect changes, consider using alternative methods like ngDoCheck to update the component's value

Within the childComponent @input() method, I am sending an array of objects where each object has 3 properties: name, id, and selected (boolean). My goal is to change only the selected property in the array and pass it to the child component for rendering. However, the changes are not being detected.

I have experimented with using ngDoCheck, which does work but runs continuously, so I am seeking a more efficient alternative solution. Is there any other way to achieve this?

I also attempted to use ngOnChanges, but since only the value is changing and not the reference, it did not work as expected.

parent.ts

type model={
name:string,
id:int,
selected:boolean
}

public dataArray:model[]=[];

parent.html

  <child-component>
    *ngFor="let item of dataArray;"
    [item]="item"
  ></child-component>

child-component.ts

@Input() public item:model;

child-component.html

<h3>{{item | json}}</h3>

Initially, when passing the array for the first time, the child component successfully renders the values. However, after making changes to the array, those changes are not reflected in the child component.

For example, let's consider two objects:

First Time:
[
{name:"item1",id:1,selected:false},
{name:"item2",id:2,selected:false}
]
After Updating:
[
{name:"item1",id:1,selected:true}, // 'true' is updated
{name:"item2",id:2,selected:false}
]

Subsequently, after modifying the array, the child component fails to detect these changes.

If I resort to using ngDocheck, the functionality works fine; however, due to its continuous execution, I prefer not to rely on it.

Answer №1

Whenever you need to update a property of an item in your array, it is necessary to modify the reference of the list.

For example:

// Assuming a simple data model for demonstration
function updateItemProperty<T extends { id: string; propToUpdate: number}>(itemToUpdate: T, allItems: T[]) {
  // Updating the desired element
  itemToUpdate.propToUpdate *= 2;
  
  // Using Array.prototype.filter will create a new referenced array triggering change detection
  const updatedItems = allItems.filter((entry) => entry.id === itemToUpdate.id ? itemToUpdate : entry);

  // Pass this updated array to the child component to reflect changes
  return updatedItems;
}

I hope this explanation was useful!

Answer №2

When passing a manipulated array or data from parent to child in the above scenario, ngOnChanges will not detect changes.

To solve this issue, I am now updating my array using the spread operator:

this.dataArray=[...this.data]

For more details, you can refer to this question Angular2 change detection: ngOnChanges not firing for nested object

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

The JSONP request failed with an error stating: ReferenceError: document is not defined

My internship project involves developing a mobile application based on the website www.claroline.net using Nativescript and Angular 2. I have successfully implemented the login function, allowing users to sign in to the app. Next, I need to integrate not ...

Data types for keys and values in TypeScript

interface A { a?: number }; interface B { a?: string }; function replicate< Source extends object, Destination extends { [key in keyof Source]?: (1) } >( source: Source, key: keyof Source, destination: Destination, converter: ...

How can I modify the pristine state of NgModel in Angular 2 using code?

Whenever you update the NgModel field, it will automatically set model.pristine to true. Submitting the form does not change the "pristine" status, which is expected behavior and not a bug. In my situation, I need to display validation errors when the fo ...

The isMobile variable from useSettings is failing to update correctly when the window is resized in a Next

I’ve encountered an issue with determining the device type (mobile, tablet, or desktop) in my Next.js application. I’ve utilized the is-mobile npm package to identify the device type and passing this data through settings. However, the isMobile flag fa ...

The footer moves upwards when a file is downloaded

I am facing an issue with my website footer and its CSS styling. #footer { position: absolute; bottom: 0; width: 100%; height:8rem; } The main goal is to keep the footer at the bottom of the page, regardless of the amount of content on th ...

Utilize the findIndex method to search for an element starting at a designated index

Below is a snippet of code that I have: private getNextFakeLinePosition(startPosition: number): number{ return this.models.findIndex(m => m.fakeObject); } This function is designed to return the index of the first element in the array that has ...

Issues related to the Angular Http module

When attempting to launch my app, I encountered the following error: ERROR Error: StaticInjectorError(AppModule)[ApiUserService -> HttpClient]: StaticInjectorError(Platform: core)[ApiUserService -> HttpClient]: NullInjectorError: No provide ...

How can the adapter pattern be implemented in Angular when dealing with an HTTP response containing an array of objects?

Using the adapter pattern in Angular, I have successfully adapted Http response to an 'Invoice' object. However, I am facing a challenge when one of the properties inside the 'Item' is an array. In this scenario, the 'items' ...

Creating a custom grid drag and drop feature within Angular Material adds a dynamic element to your application, going beyond basic list

According to the angular material documentation, creating a pure grid drag and drop feature is not straightforward. One solution I have come up with involves using multiple horizontal lists where items can only be dragged within their own row, resulting in ...

Progress Bar Modules

I am currently working on creating a customizable animated progress bar that can be utilized as follows: <bar [type]="'health'" [percentage]="'80'"></bar> It is functional up to the point where I need to adjust different p ...

Troubleshooting: Angular 2 property binding animations not functioning as expected

I'm attempting to create a fade-in animation for a div element. Here is the code snippet: import { Component, trigger, state, style, transition, animate, keyframes, group } from '@angular/core'; @Component( ...

Create a NfcV Write Lock Block instruction

Seeking to make data on a NXP ICODE SLIX SL2S2002 tag type 5 (ISO 15693) read-only by utilizing the WRITE SINGLE BLOCKS command through the NfcV object in an app based on Ionic: private readonly cmdISO15693 = { READ_SINGLE_BLOCK: 0x20, WRITE_SI ...

The table is not properly displaying the data even though it is stored in the array and can be seen in the browser console. What could be causing this issue with my

<tr *ngFor="let animal of readAnimal"> <th scope="row">{{ animal.id }}</th> <td>{{ animal.name }}</td> <td>{{ animal.description }}</td> <td>{{ animal.creat ...

Rearrange an element in an array from last to first position using typescript

I am working with an array that looks like this var column = ["generic complaint", "epidemic complaint", "epidemic1 complaint", "epidemic2 complaint", "bal vivah", "name"] My goal is to move the last element of the array to the first position, resultin ...

Tips for positioning buttons within the MdDialog md-dialog-actions section

Can a button be aligned on the left in the MdDialog's md-dialog-actions block, while having two buttons aligned to the right? If you check out this example of what I'm working on, how can I separate the Yes and No buttons in the first modal? (Re ...

Resetting the selected value in an Angular2 select element after the user makes a change

I have a dropdown menu which the user can select an option from. Initially it has a default value and when the user makes a new selection, I need to ask for confirmation by showing a message "are you sure?". If the answer is NO, then I should revert back t ...

Creating a TypeScript definition file to allow instantiation of a module

I'm encountering an issue with creating a declaration file for an existing module. When using JavaScript, the module is imported using the following syntax: var Library = require('thirdpartylibs'); var libInstance = new Library(); I have ...

Is it possible to target a specific element using Angular2's HostListener feature? Can we target elements based on their class name?"

Is there a way in Angular2 to target a specific element within the HostListener decorator? @HostListener('dragstart', ['$event']) onDragStart(ev:Event) { console.log(ev); } @HostListener('document: dragstart' ...

Grunt Typescript is encountering difficulty locating the angular core module

Question Why is my Grunt Typescript compiler unable to locate the angular core? I suspect it's due to the paths, causing the compiler to not find the libraries in the node_modules directory. Error typescript/add.component.ts(1,25): error TS23 ...

Retrieving Firebase data asynchronously with Angular and Firestore

Apologies if the title is a bit off, but I'm reaching out here because I'm feeling quite lost and unable to locate what I need online. To be honest, I'm not entirely sure what exactly I'm searching for. Here's my situation: I have ...