Search code examples
angularimmutabilityangular-formsangular-changedetection

Angular change detection strategy on push without immutable objects


I've been reading some articles about change detection strategy, but i have some doubts about which are the cases where makes sense to use on push strategy. Basically my doubt is about when we have nested components with binding of objects which are not immutable. I have two nested components, a parent and a child, both with change detection strategy on push. I am passing as an input to the child component a formGroup.

When i set the form as enabled on the parent component and then i call ChangeDetectorRef.detectChanges() (which should check the change detector and its children), i am not seeing the changes on the child component (for example an ngIf on child component showing stuff when the form is enabled).

What am i doing wrong or not understanding well?


Solution

  • By default, the Change Detection is run when the object reference is updated which is why it is said that change detection is run only on immutable objects.

    You have to use OnPush change detection strategy when you component solely relies on the Input() bindings to it.

    You have to run the markForChange() method on the ChangeDetectorRef inside the ngDoCheck() in the child component.

    Use this link from medium to further understand my answer.

    I have created a project and uploaded it on GitHub for the scenario you mentioned. You may use it for your reference.