1

I read many articles about change detection but didn't get clear picture how does it work and renders view. Like in react we have virtual dom and diff algorithm which renders only part of UI that has been changed by creating dom patch so similarly how does angular know which part of UI needs to be changed.

How does changes detection decide what change will be rendered/replaced in view?

Akhlesh
  • 2,389
  • 1
  • 16
  • 23

1 Answers1

3

Each component has an associated change detector object that Angular creates at runtime. The change detector object tracks all of the template bindings. When change detection runs, by default, it dirty checks each template binding in each change detector object – i.e., it compares the previous value with the current value. If a change is detected, the new value is propagated to the DOM. So if there was only one change, only one part of the DOM is updated. The entire view is not re-rendered if a change is found... only the part that changed is affected.

My longer answer: https://stackoverflow.com/a/34570122/215945

Community
  • 1
  • 1
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
  • If i have a grid with editable cell(cell is itself a component) and i have updated the value of cell so does it re-render only cell part or whole grid ? fact is that cell value update is going to change the grid state also. – Akhlesh Apr 12 '16 at 18:53
  • 1
    @Akhlesh, it all comes down to what the bindings are in the views. If only one cell component's binding changed (because only one cell value changed), then only that cell's DOM is updated with the new value. If the grid somehow uses that cell's value in its view, then the DOM associated with the grid would also get updated. But in your case, it sounds like only the one cell's DOM will be updated. Just because the overall grid state changes (because a cell changed), doesn't mean that Angular will rerender the entire grid. It's not like other frameworks in that regard. It is more efficient. – Mark Rajcok Apr 12 '16 at 18:58
  • @Akhlesh, if your cell components are leaf components (meaning they have no child components of their own), and they only depend on an input primitive property for their value (i.e., a string or a number), you should use the `OnPush` [change detection strategy](https://angular.io/docs/ts/latest/api/core/ChangeDetectorRef-class.html) to make your cell checking much more efficient. – Mark Rajcok Apr 13 '16 at 14:27
  • Thanks Mark. Yes cells are leaf components – Akhlesh Apr 13 '16 at 18:17