组件的生命周期和指令的生命的周期唯一区别就是指令没有AfterContentInit和AfterContentChecked,因为指令没有投影。在组件或父组件发生变更检测的时候都会调用三个变更检测方法:
ngDoCheck、ngAfterContentChecked、ngAfterViewChecked
以下生成的生命周期方法即为组件生命周期执行顺序
import {
AfterContentChecked,
AfterContentInit, AfterViewChecked,
AfterViewInit,
Component,
DoCheck, Input,
OnChanges, OnDestroy,
OnInit
} from '@angular/core';
@Component({
selector: 'app-life-cycle',
templateUrl: './life-cycle.component.html',
styleUrls: ['./life-cycle.component.scss']
})
export class LifeCycleComponent implements OnChanges,OnInit,DoCheck,AfterContentInit,AfterContentChecked,AfterViewInit,AfterViewChecked,OnDestroy {
@Input() title: string = "def";
//在构造函数里不能获取最新的输入属性值
constructor() {
console.log("constructor",this.title);
}
//在输入属性发生变化的时候调用
ngOnChanges(): void {
console.log("ngOnChanges",this.title);
}
//属性和指令初始化完成调用
ngOnInit(): void {
console.log("ngOnInit");
}
//首次变更检测完调用
ngDoCheck(): void {
console.log("ngDoCheck");
}
//投影初始化完调用
ngAfterContentInit(): void {
console.log("ngAfterContentInit");
}
//投影变更检测完调用
ngAfterContentChecked(): void {
console.log("ngAfterContentChecked");
}
//视图初始化完调用
ngAfterViewInit(): void {
console.log("ngAfterViewInit");
}
//视图变更检测完调用
ngAfterViewChecked(): void {
console.log("ngAfterViewChecked");
}
//组件销毁完调用
ngOnDestroy(): void {
console.log("ngOnDestroy");
}
}