Angular

Angular Component Guide: How ngOnChanges Hook Works ?

Angular is a very modern and powerful framework comes with tons of core features like dependency injection, content projection, advanced component lifecycle hooks and so on. Some developers claim it makes angular complex and cumbersome. In my opinion it makes angular productive. You can develop large scale application with less amount of time and complexity. Angular provides lots of handy features which you don’t have to develop it from scratch.

In this post I would like to focus lifecycle hooks, what they are and how we can use effectively. I see that most of developers new to angular makes a lot of mistakes. I believe it is because we are tend to avoid reading documentation 😀 But no worries. If you don’t know anything about the hooks or you are looking for some usefull tips, we will cover in this post starting with ngOnChanges

Let discover ngOnChanges()

This is the first hook invoked in the component. Angular calls the ngOnChanges when the inputs initialized and updated. But there is one critical detail about this hook. If your component doesn’t have any input Angular will never invoke ngOnChanges.

When ngOnChanges called, angular pass a parameter with type of SimpleChanges. It is a dictionary of input properties that contains previous and current value of the propery.

When should we use ngOnChanges() ?

Most of developers using angular don’t even know there is a such hook! It is quite handy specially when you are working with 3.rd party libraries.

1. Working With 3.rd Party Libraries

When you are working with 3.rd party libraries sometime you are not able to update the state using angular lifecycle. Let say you are showing some live GPS data on google maps. When you receive the latest coordinate, you need to update the position of the coordinate right ? We created the marker ngOnInit hook with the first coordinate, but then when the coordinate has changed, we can setup ngOnChanges() hook and listen following changes.

Update Map Center When Location Input Has Changed

2. Making recurring API calls

If your components needs to fetch some data from a external service or API based on input. You can easly listen input changes using ngOnChanges and make consecutive api calls.

Fetch Step File From Server When FileId Input Property Has Changed

3. Component Validation and Security

If your component is fragile and relies what you get from input properties, you do better if you validate your input values using ngOnChanges. You can easily filter out invalid values and show senseful messages.

Validate Data Type When Input Property Has Changed

4. Debugging The Component

When you are developing a component that have input properties frequently updated. You might need to use ngOnChanges when you debug the component to check everything is working fine.

Debug Component When Input Properties Has Changed

When should we NOT use ngOnChanges() ?

1. Initialization Logic

When you are perform some initialization logic that should be made one time, you should use ngOnInit hook over ngOnChanges. Since ngOnChanges called when the input properties change, it might break your initialization configuration when it get called multiple times.

2. Cleanup Operations

When the component needs to perform some cleanup logic: If the component needs to perform some cleanup logic when it is destroyed, then ngOnDestroy should be used instead of ngOnChanges.

Conclusion

Hooks are very powerfull and handy features. We should use more often instead trying to develop a workaround which we can achieve with the hooks in couple line of codes. But you need to be carefull when you are using it. For example in the ngOnChanges if you emit an event that might effect input properties in the parent component. It might leads sirious performance problems. We must be precise when should we use hooks, specially using ngOnChanges.

I tried to explain hooks and specially ngOnChanges in general. If you have questions about hooks or anything about angular feel fre to ask me.

teoman.me

Recent Posts

Angular 17 ile Bizi Neler Bekliyor ?

Herkese Merhabalar. Bildiğiniz üzere bu ay Angular 17 yepyeni bir imaj çalışması ile birlikte yayına…

1 year ago

OpenLayers Nasıl Kullanılır ?

Herkese merhaba arkadaşlar. Önceki yazımızda openlayers nedir ve neden kullanmalıyız sorunu yanıtlamıştık. Popüler harita kütüphanelerinden…

1 year ago

Openlayers Nedir ? Neden Tercih Etmeliyiz ?

Merhaba arkadaşlar. Eğer CBS (Coğrafi Bilgi Sistemleri) dünyasına yeni yeni adımlar atıyorsanız adını sık sık…

1 year ago

Angular NGXS – 5 Dakikada State Management! Part I

Herkese merhabalar. Bugün angular ekosisteminde NGXS kullanarak nasıl state management yapacağımızı inceleyeceğiz. Angular state management…

1 year ago

Angular vs React! Hangisini Tercih Etmeliyiz ?

Herkese Merhaba. Bu yazımızda frontend camiasında faaliyet gösteren herkesin aklındaki o soruya bir açıklık getireceğiz.…

1 year ago

Angular Template Driven Form Nedir ? Nasıl Kullanılır ?

Uzun bir aradan sonra herkese merhaba :) Angular Template Driven Form Nedir, Ne işe yarar…

1 year ago