简体   繁体   English

当有Parent Component和Child Component时,为什么在Parent OnInit之前调用Child Constructor?

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

My code has two components -我的代码有两个组成部分 -

  1. Parent家长
  2. Child孩子

Relevant code and output below -相关代码和下面的output -

parent.component.html父组件.html

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

parent.component.ts父组件.ts

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

child.component.ts 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控制台中的 output

 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.我无法理解为什么在 Parent Constructor 之后没有立即调用 Parent OnInit。

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 .首先,实例化 class ,然后调用 class 的方法,如果组件没有@Input则为OnInit

If it does have then it's OnChanges that is fired first.如果确实有,那么首先触发的是OnChanges

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM