Search code examples
angulartypescriptngoninitngonchanges

What is the difference between Angular ngOnInit() and ngOnChanges()?


Angular provides lifecycle hook ngOnInit() and ngOnChanges() by default. Why should ngOnInit be used, if we already have a ngOnChanges? And constructor also.


Solution

  • How a form need be setup

    0. Static design Html markup should hold how the design is structured and laid out. Any permanent classes are to be applied directly in markup.

    1. Constructor

    Setup dependencies, like services, providers, configuration etc. These enable the component to manage itself along with interact with other elements.

    2. Initializer (ngOnInit)

    Populates form elements like dropdowns etc when their values are to be retrieved from external source, rather than being known at design time. This is to be done once only to setup the initial rendering of the form

    3. Input changes (ngOnChanges)

    Runs on every change on any input, and perform any action which gets triggered by that particular control. For example, if there are multiple inputs and on any validation failure on a single one, you need to focus on the failed control and disable all others, you can do it here. Useful for validation logic.

    Not to be used to handle other control's layout and structure.

    This often runs recursively if one control impacts others so logic has to be carefully designed.

    If you want to prevent this from running, you can disable the Angular change detection and manually handle the state yourself.

    4. Control's event handlers Here you take in the final value of the control and use it to perform manipulation of other controls in the form. As soon as you change the value of other controls, the ngOnChanges event fires again.