6

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?

Jota.Toledo
  • 27,293
  • 11
  • 59
  • 73
Emanuel Pinho
  • 136
  • 1
  • 6

1 Answers1

7

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.

Arjun Panicker
  • 730
  • 1
  • 8
  • 20
  • Thanks for the explanation. After read the article i have only one doubt. Isn't that the same thing between having the default strategy and having onpush but mark for check all the times ngDoCheck is called? – Emanuel Pinho Mar 01 '18 at 23:00
  • The `markForCheck()` is only used when `OnPush` strategy is used. Check this link: https://angular.io/api/core/ChangeDetectorRef . If you are going to use the `Default` strategy, I guess you will have to use the `detach()` and `detectChanges()` together (according to my understanding). – Arjun Panicker Mar 02 '18 at 05:58