生命周期
Angular从程序引导启动、再到创建与销毁组件动作都有一系列钩子事件,它允许我们在某个阶段有机会做点处理。
名称 | 说明 | 范围 |
---|---|---|
constructor | 构造函数 | 指令和组件 |
ngOnChanges | 属性变更通知 | 指令和组件 |
ngOnInit | 组件初始化 | 指令和组件 |
ngDoCheck | 每一次变更检测时 | 指令和组件 |
ngAfterContentInit | 子组件初始化后 | 组件 |
ngAfterContentChecked | 子组件变更检测之后 | 组件 |
ngAfterViewInit | 组件初始化后 | 组件 |
ngAfterViewChecked | 组件每次变更检测之后 | 组件 |
ngOnDestroy | 初始销毁之前 | 指令和组件 |
step1:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'untitled2906';
//参考网址:https://cipchk.gitbooks.io/angular-practice/content/component/lifecycle.html
/**
* 组件或指令初始化完成后数据变更检测前触发。
* 因此,这个时候组件的模板 template 值已经写入DOM树当中,这个时候在这里做数据请求与处理再适合不过了。
*/
ngOnInit() {
console.log('ngOnInit')
}
/**
每次变更检测(不管是否有数据)周期时触发,这是一个高频率触发,所以不要在这时在做一些复杂的操作。
*/
ngDoCheck() {
console.log('ngDoCheck')
}
/**
* AfterContent 系列钩子优先于 AfterView
*/
ngAfterContentInit() {
console.log('ngAfterContentInit')
}
/**
* 每次变更检测(不管是否有数据)周期时触发,优先级略低于 ngDoCheck()。
*/
ngAfterContentChecked() {
console.log('ngAfterContentChecked')
}
/**
* AfterContent 系列钩子优先于 AfterView
*/
ngAfterViewInit() {
console.log('ngAfterViewInit')
}
/**
* 每次变更检测(不管是否有数据)周期时触发,优先级略低于 ngDoCheck()。
*/
ngAfterViewChecked() {
console.log('ngAfterViewChecked')
}
/**
* 组件或指令初始销毁之前触发。
*/
ngOnDestroy() {
console.log('ngOnDestroy')
}
}
step2: run ,执行顺序
ngOnInit
ngDoCheck
ngAfterContentInit
ngAfterContentChecked
ngAfterViewInit
ngAfterViewChecked
ngDoCheck
ngAfterContentChecked
ngAfterViewChecked
end