CodexBloom - Programming Q&A Platform

Angular 15 ChangeDetectionStrategy.OnPush not updating nested component with input changes

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
angular change-detection onPush TypeScript

I'm trying to debug I've been struggling with this for a few days now and could really use some help... I'm working on a project and hit a roadblock. I've been banging my head against this for hours... I'm having trouble with a nested component that uses `ChangeDetectionStrategy.OnPush`. The parent component is passing down an input object to the child component, but it seems that the child component is not updating when the properties of the input object change. Here's a simplified version of my setup: ```typescript // Parent Component (parent.component.ts) import { Component } from '@angular/core'; @Component({ selector: 'app-parent', template: `<app-child [data]='data'></app-child>` }) export class ParentComponent { data = { name: 'Initial Name', age: 25 }; updateData() { this.data.name = 'Updated Name'; // This does not trigger change detection } } // Child Component (child.component.ts) import { Component, Input, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-child', template: `Name: {{ data.name }} Age: {{ data.age }}`, changeDetection: ChangeDetectionStrategy.OnPush }) export class ChildComponent { @Input() data!: { name: string; age: number; }; } ``` I expected the child component to reflect changes to the `data` object, but it doesn't seem to do that when I call `updateData()` from the parent. The change detection isn't triggered, and hence the view in the child remains the same. I've tried using `ChangeDetectorRef.markForCheck()` in the child component after the input change, but it still doesn't work as expected: ```typescript // Inside child.component.ts after setting @Input() ngOnChanges() { this.cd.markForCheck(); // cd is ChangeDetectorRef } ``` I also considered using immutable objects or creating a new reference for `data`, but that doesn't feel like a clean solution. Is there a best practice I should follow to ensure that the child component updates correctly when the input object properties change? How can I handle updates to nested properties while still using `OnPush`? Any insights would be greatly appreciated! Is there a better approach? I'm working on a service that needs to handle this. What's the best practice here? I'd really appreciate any guidance on this. I'm working on a REST API that needs to handle this. What am I doing wrong? Has anyone dealt with something similar?