Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When there is a Parent Component and a Child Component, why is the Child Constructor called before the Parent OnInit?

Tags:

angular

My code has two components -

  1. Parent
  2. Child

Relevant code and output below -

parent.component.html

<p>parent works!!</p>
<app-child> </app-child>

parent.component.ts

export class ParentComponent implements OnInit {
  constructor() {
    console.log('Logged by Parent constructor');
  }

  ngOnInit() {
    console.log('Logged by Parent OnInit');
  }
}

child.component.ts

export class ChildComponent implements OnInit {
  constructor() {
    console.log('Logged by Child Constructor');
  }

  ngOnInit() {
    console.log('Logged by Child OnInit');
  }
}

output in console

Logged by Parent constructor
Logged by Child Constructor
Logged by Parent OnInit
Logged by Child OnInit

I am unable to understand why Parent OnInit is not called immediately after Parent Constructor.

Can I please get an explanation on execution flow that is happening under the hood?

like image 386
Krishi Avatar asked Sep 12 '25 21:09

Krishi


1 Answers

Constructors are called before lifecycle methods. At first, class is instantiated and then the method of a class is called, which is OnInit if component doesn't have @Input.

If it does have then it's OnChanges that is fired first.

like image 52
Chaka15 Avatar answered Sep 14 '25 11:09

Chaka15