Angular

Angular Component Guide: How ngOnInit Hook Works ?

Hi everyone! In the previous post we talked about ngOnChangesHook. When we use it or when we not. Today we will proceed with the ngOnInit Hook. It is one of the most common hook used in angular. When you create a component using command line it will automatically implemented. It is the angular version of the componentDidMount hook in React.

Since it is quite known and basic hook I will try to keep this post short. I’m planning to focus other hooks as much as possible. Sorry if you feel like Theoden.

Let Discover ngOnInit()

When the component constructed, angular calls ngOnChanges (in case of input props defined) then it calls the ngOnInit hook.If there is no input property defined in the component, Angular still calls ngOnInit. So we can say it is kinda first hook that called in the component in any case.

It is called only once when your input properties set so you can make some adjustment, validations and api calls. It is important to know when the ngOnInit called, our template is not rendered yet. Almost any dom manupilation on the ngOnInit will fail. So you should avoid to manupulate dom on this hook.

When should we use ngOnInit() ?

1. Fetch Data From Services

Since ngOnInit runs almost before everything and it only called once, it is best practice to make your service calls here. I see that some people uses constructor to make api calls. Which could be dangerous because if let say in the future when you need to pass some input value to call it will be fail. Because input properties is not set when the component constructured.

Fetch Data From Service Using ngOnInit Hook

2. Setup Component & Initialize Properties

It is best practice to initialize your properties and setup your component in the ngOnInit. Since angular has MVVM logic behind. It is better to setup everything before your template rendered. You can avoid template failures, check conflicts and performance problems due to repated template rendering. Common examples;

  • Registering form elements
  • Subscribing observables
  • Initializing properties with default values
  • Validating input properties
  • Configuring component based on inputs or services
  • Setting up external libraries

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 ngOnInit hook when you try to access dom elements it will most likely fail because template is not initialized yet. You might consider to use ngAfterViewInit instead.

I explained common use cases of ngOnInit. Of course there are lots use cases we are not stated here. But the main logic here is generally same. We are preparing our component for later stages. If you are not comfortable to use ngOnInit feel free to share with or if you have any questions about hooks or angular in general, don’t hesitate to ask. I am happy to help 🙂

You can also check other posts to get to know more about the Angular!

Component Guide: How ngOnChanges Hook Work

Turn Your Component Into Form Control Using ControlValueAccessor

Interceptor Nedir, Nasıl Kullanılır ?

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…

12 months 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…

12 months 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…

12 months 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