My code has two components -
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With