Child components in Angular may fail to detect changes in input properties

In my parent component, I have a property named documents which is an Array used to pass document objects to a child component.

However, when I add a new document to the documents array, the child component's view does not update. Can someone point out what I might be doing wrong?

This is the snippet of code in the parent component where the documents array is updated:

// handle the data that comes back from the dialog
 createDialog.afterClosed().subscribe(
  data => {
    if (data){

      // persist vital signs
      this.documentService.saveDocument(data.newDocument);

      this.documents.push(data.newDocument);

      // update the existing document bucket the document belongs to
      this.loincToDocumentsMap.get(data.loincCode)?.folderContent.push(data.newDocument);

    }
  }
);

Here is the child component structure:

@Component({
  selector: 'document-list',
  templateUrl: './document-list.component.html',
  styleUrls: ['./document-list.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class DocumentListComponent implements OnInit, OnChanges {

  @Input() documents: DocumentReference[] = [];
  
  ....
}

This is how the child component is utilized in the parent component:

<document-list *ngIf="showListUi" [documents]="documents"></document-list>

I am seeking guidance as the same approach has worked with other components within the same parent component and I cannot figure out the difference. Another child component updates correctly while this one does not.

Update-1:

After adding this line, the change detection starts working. But why?

this.documents = this.documents.filter(document => {
        return true;
      })

Update-2: Thank you everyone for your assistance; solutions can be found in the answers below :)

Answer №1

When it comes to Angular change detection, it solely focuses on object identity rather than object content, which means that it does not detect inserts or removals.

For further information, you can refer to the following links: and

Answer №2

If your UI is not updating, it could be due to the OnPush change detection method being used. With OnPush, changes detected will only trigger a render if the pointer of the array changes without checking the content within the array itself. Therefore, simply adding an item to the array may not cause the array's pointer to change.

To address this issue, there are a few potential solutions:

  • Disable OnPush
  • Create a new array
  • Use observables for the array

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

Ways to retrieve the length of the parent array within a component in AngularJS

Is there a way to access the value of a property in the parent from within a component? Parent: export class Animal{ animalID ?: Array<number>; { Child: import {Component, Input} from '@angular/core'; import {Animal} from '../anim ...

Obtain both the key and value from an Object using Angular 2 or later

I have a unique Object structure that looks like this: myCustomComponent.ts this.customDetails = this.newParameter.details; //the custom object details are: //{0: "uniqueInfo", // 5: "differentInfo"} The information stored in my ...

Angular2 plugin for redacting content

I'm attempting to integrate Redactor with additional plugins, but I'm encountering an issue where the counter plugin displays 0 words and 0 characters after the page has loaded. { words: 0, characters: 0, spaces: 0 } To address this pro ...

What is the most efficient way to apply multiple combinations for filtering the information within a table?

I'm facing an issue with my Angular project. I have 4 select boxes that allow users to apply different filters: office worker project name employee activities The problem I'm encountering is the difficulty in predicting all possible combination ...

While utilizing Ionic to upload images to a server, I encountered the FileTransferError error code 3

I have successfully uploaded an image from the gallery, but I am facing issues while uploading multiple images at once. Here is the code snippet I am using: pictureUpload(x){ // x represents the file path like - file:///storage/emulated/0/Download/palak ...

Strangely behaving data binding when using socket.io

Recently, I've been experiencing some strange behavior while developing a socket.io app with Angular 2 on the frontend. This unusual issue seems to be related to the interaction between Angular 2 and socket.io, as I have never encountered anything lik ...

Configure Typescript to skip errors for a specific file

Is there a way to suppress TypeScript errors for specific files using the tsconfig.json file? I am aware of the exclude property mentioned on the TypeScript website, but that's not exactly what I'm looking for. As it's explained: If a fil ...

React and TypeScript are not compatible - there is no overload that matches this call

Check out my demo This is a basic application that utilizes the GitHub api to showcase users and their avatars. Included in this app is a Users component which organizes the user data stored in the state. In order to display the data from the state, a U ...

What is the best way to organize information within a template using a *ngFor loop without needing to include functions directly in the template?

When working with Angular 11, I encountered a scenario where a Component receives an array of data from an external source that needs to be displayed in a template using a *ngFor loop with custom formatting. While my initial approach involved creating func ...

What could be the reason that the _.sample function in lodash is producing a return type of number

Sample Scenario 1 const myNumber = _.sample([1, 2, 3]); // Anticipated data type: number // Real data type: number Sample Scenario 2 const arr = [1, 2, 3] const myNumber = _.sample(arr); // Anticipated data type: number // Real data type: number | undefin ...

An issue has occurred while utilizing Angular

I'm diving into the world of Angular and encountering some errors as I try to execute this code. An unexpected token is causing trouble. A constructor, method, accessor, or property was expected. The left side of a comma operator seems to be unused ...

How can I set ion-option to be selected by tapping instead of having to click OK?

Currently, I am developing a mobile application and have encountered a scenario in which I utilized ion-option with ion-select, resulting in successful functionality. However, I am now aiming to remove the OK/CANCEL button so that users do not need to clic ...

The type 'string' cannot be assigned to the type '"GET" | "get" | ...'

In my custom hook, I utilize the axios library for making requests: const useCustomHook = ({ endPoint = "", method = "GET", options = {} }) => { const [data, setData] = useState([]); const [request, setRequest] = useState<AxiosRequestConfig> ...

Transform an unidentified function into a new type using TypeScript

Consider the following code snippet: type T = (x: number) => boolean; let fn = function(a: string, b: boolean, c: T){}; fn('yes', true, ()=> { }); Unfortunately, this code will not compile. The goal is to cast the anonymous function to ...

OnPush strategy and template updates: Propagating modifications to the parent component

I am currently facing an issue with a parent component that consists of two templates. The first template simply displays data-bound text, while the second template contains a child component responsible for updating the data model. Both the parent and chi ...

Issue: The element 'app-header' is unrecognized even after including 'CUSTOM_ELEMENTS_SCHEMA'

Despite the 'app-header' component being rendered in the browser, the content in the relevant "header.component.ts" or "header.component.html" files is not appearing on the screen. https://i.sstatic.net/MfKVk.png Error: 'app-header' is ...

Guide to exporting a ReactJS + Typescript component to be used in Vanilla JavaScript and HTML

I have a ReactJS component along with its sub-components styled with CSS. I'm looking for a way to export my component for VanillaJS and HTML without having to import React@17 or 18. If there is an easier method or any alternative suggestions instead ...

Are you harnessing the power of Ant Design's carousel next and previous pane methods with Typescript?

Currently, I have integrated Ant Design into my application as the design framework. One of the components it offers is the Carousel, which provides two methods for switching panes within the carousel. If you are interested in utilizing this feature using ...

Guide to limiting interceptor scope to a specific module in Angular

Below is the angular interceptor used to replace the auth token: @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor( ) { } intercept( request: HttpRequest<any>, next: HttpHandler ): Observable<H ...

Tips for implementing absolute paths and baseUrl in TypeScript compiler

When I bundle a package using tsc, I am getting incorrect output. Here is the structure of my project directory: common └── index.ts types ├── action.ts ├── index.ts └── request.ts utils ├── event.ts ├── index.ts ├─ ...