9

From these two posts:

I understand how the DOM updated when the 'Change Detection' has occurred. The thing I do not understand from "Everything you need to know about change detection in Angular" is how Angular keeps track of what properties have beed used inside the function and therefore when it should run the 'Change Detection'.

Let's assume this is the parent Component view.

<child [prop]="func()"></child>

where func() is

func() { return this.parentProp }

and parentProp has not been used in the template. If and when parentProp gets changed by a service, how does the Angular knows that func() depends on parentProp and therefore should trigger a 'Change Detection' and update the view.

Tom de Geus
  • 5,625
  • 2
  • 33
  • 77
nikrooz
  • 121
  • 1
  • 5

1 Answers1

15

Angular doesn't know or care about the content of the function.

Angular will call func() every time change detection runs and compare if the previous result is the same as the current result.

Because calling a function and comparing the result is much more expensive than just comparing the previous value with the current value, it's better to use an event to update a property with the function result and bind the view only to the property, instead of to a function directly.

If the function returns different values on subsequent calls (with the same parameter values) you'll get an exception in development mode like

the model has changed since it was last checked

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    So maybe my question is basic than that. If a component's property which does not appear on the template changes, does the Change Detection runs? – nikrooz Mar 16 '18 at 12:38
  • It's not property changes that cause change detection to run, it's change detection that checks if properties have changed. When change detection is run depends on your settings (for example by setting `changeDetection: ChangeDetectionStrategy.OnPush`). Change detection usually happens when an event handler was called and its execution has completed (which is recognized by Angulars zone) or when it's explicitly invoked by `ChangeDetectorRef.markForCheck()`. – Günter Zöchbauer Mar 16 '18 at 12:42
  • 1
    Is it just as expensive to use getter methods instead of an actual function? – herondale Mar 08 '19 at 05:36
  • 4
    Yes, it's the same, just the syntax is a bit different. – Günter Zöchbauer Mar 08 '19 at 05:43