生命周期
生命周期列表
接口 |
描述 |
ngOnChanges()
|
1.仅当设置@Input才会触发。2.组件绑定的属性修改时,触发。 |
ngOnInit() |
每当一个或多个数据绑定输入属性更改时 调用。 |
ngOnInit() |
在Angular首先显示数据绑定属性并设置指令/组件的输入属性以后,初始化指令/组件。调用一次,后第一 ngOnChanges()。 |
ngDoCheck()
|
检测Angular没法或没法自行检测到的更改并采起措施。在每次更改检测期间(ngOnChanges()和以后)当即调用ngOnInit()。 |
ngAfterContentInit() |
在Angular将外部内容投影到组件的视图/指令所在的视图中后做出响应。第一次 调用以后ngDoCheck()。 |
ngAfterContentChecked()
|
Angular检查投影到指令/组件中的内容后响应。在ngAfterContentInit()及以后的调用ngDoCheck()。 |
ngAfterViewInit()
|
Angular初始化组件的视图和子视图/指令所在的视图后响应。第一次 调用以后ngAfterContentChecked()。 |
ngAfterViewChecked()
|
Angular检查组件的视图和子视图/指令所在的视图后响应。在ngAfterViewInit()及以后的调用ngAfterContentChecked()。 |
ngOnDestroy()
|
在Angular销毁指令/组件以前进行清理。取消订阅Observable并分离事件处理程序,以免内存泄漏。在 Angular销毁指令/组件以前 调用。 |
单组件生命周期调用过程
custructor
|
ngOnChanges →---------------------------------
| |
ngOnInit //call only once |
| |
ngDoCheck // call after every change ←----------
|
ngAfterContentInit //call only once after docheck
|
ngAfterContentChecked // call only once after ngAfterContentInit
|
ngAfterViewInit //call only once after ngAfterContentChecked
|
ngAfterViewChecked //call only once after ngAfterViewInit
|
ngOnDestroy //call only once
复制代码
多组件生命周期调用过程
custructor
|
child constructor
|
ngOnChanges →---------------------------------
| |
ngOnInit //call only once |
| |
ngDoCheck // call after every change ←----------
|
ngAfterContentInit //call only once after docheck
|
ngAfterContentChecked// call only once after ngAfterContentInit
|
ngAfterViewInit //call only once after ngAfterContentChecked
|
ngAfterViewChecked//call only once after ngAfterViewInit
|
ngOnDestroy //call only once
复制代码
- 全部组件、指令的constructor逐级调用完毕,
- 在逐个各组件、指令依次调用生命周期钩子
日志参考以下:
this is app constructor heroes.component.ts:21
this is heros parent constructor..... hero-detail.component.ts:12
this is child constructor.... app.component.ts:12
app init... heroes.component.ts:38
this is parent changes... heroes.component.ts:30
this is parent init hero-detail.component.ts:20
this is child changes.... hero-detail.component.ts:16
this is child init....复制代码
this is app constructor heroes.component.ts:22
this is heros parent constructor..... hero-detail.component.ts:13
this is child constructor.... app.component.ts:12
app init... app.component.ts:18
this is app docheck app.component.ts:22
this is app content init heroes.component.ts:39
this is parent changes... heroes.component.ts:31
this is parent init heroes.component.ts:43
this is parent docheck heroes.component.ts:46
this is parent content init hero-detail.component.ts:21
this is child changes.... hero-detail.component.ts:17
this is child init.... hero-detail.component.ts:24
this is child docheck hero-detail.component.ts:28
this is child content init hero-detail.component.ts:28 复制代码
本文做者:前端首席体验师(CheongHu)
联系邮箱:simple2012hcz@126.com
版权声明: 本文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!复制代码