ngDoCheck vs ngOnChanges

mabdullahse
1 min readSep 26, 2021

--

ngDoCheck detects each change

Before we dive into ngDoCheck, let’s first understand how the angular change detection algorithm works ?

The default algorithm of angular for change detection looks for differences by comparing input-bound properties value by reference, understand. Cool. 🙌

Limitation of ngOnChanges()

Due to default behavior of angular change detection, ngOnChanges can’t detect if we change a property of an object or push an item into an array.

For example: we are passing down an object or array to child component form parent

<child-component[collection]="myCollection"></child-component>

When it's one of property change or if we push an item into array in parent, it won’t catch in ngOnChanges hook in child component because of default angular change detection behavior mentioned above 😔. But ngDoCheck do, so it's the right place to write the logic in this case.

ngDoCheck() 🤩 !

Detect deep changes like a property change in object or item is pushed into array even without reference change. Amazing Right 😊

Angular recommends either ngOnChanges or ngDoCheck to write custom code of same input property change. Avoid writing complex code in ngDoCheck hook

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

mabdullahse
mabdullahse

No responses yet

Write a response