angular组件生命周期可以分为几个阶段,每个阶段
1、构造函数(constructor)
- 在angular创建组件实例时调用
- 用于依赖注入和其他初始化操作
- 注意:不要在这里执行复杂的逻辑和异步操作
2、输入属性检查(Input Property Check)
- ngOnchange:当组件的输入属性(@input)发生变化时调用。
- 接收一个SimpleChanges对象,包含所有发生变化的输入属性及其当前值和前一个值
3、初始化
- ngOnInit: 在第一次ngOnChanges调用之后调用,或者如果没有输入属性,则在构造函数之后立即调用
- 用于执行初始化逻辑,如订阅服务、设置定时器
4、检查
- ngDocheck: 每次变更检测运行时调用,用于检测Angular无法检测的变化
- 通常用于自定义变更检测逻辑
5、子组件检查
- ngAfterContentInit:在组件的内容投影(Content Projection)初始化后调用
- 用于处理投影到组件中的内容
- ngAfterCOntentChecked: 每次变更检测运行后,且内容投影检查完成后调用
6、视图检查
- ngAfterViewInit: 组件视图(模板)初始化后调用
- 用于处理组件的视图
- ngAfterViewCHecked: 每次变更检测运行后,且视图检查完成后调用
7、销毁
- ngOnDestroyed: 在组件被销毁之前调用
- 用于执行清理操作,取消订阅,清除定时器
调用顺序
1、构造函数: constructor()
2、输入属性检查:ngOnChange()
3、初始化:ngOnInit()
4、检查:ngDocheck()
5、子组件检查:
- ngAfterContentInit()
- ngAfterContentChecked()
6、视图检查:
- ngAfterViewInit()
- ngAfterViewChecked() //视图更新完成之后调用
7、销毁: ngOnDestroyed()
示例:
import { Component, OnInit, OnChanges, SimpleChanges, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy } from '@angular/core';
@Component({
selector: 'app-lifecycle',
template: `
<p>生命周期示例</p>
<p>输入属性: {{ inputProperty }}</p>
`,
styles: []
})
export class LifecycleComponent implements OnInit, OnChanges, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy {
@Input() inputProperty: string;
constructor() {
console.log('Constructor called');
}
ngOnChanges(changes: SimpleChanges): void {
console.log('ngOnChanges called', changes);
}
ngOnInit(): void {
console.log('ngOnInit called');
}
ngDoCheck(): void {
console.log('ngDoCheck called');
}
ngAfterContentInit(): void {
console.log('ngAfterContentInit called');
}
ngAfterContentChecked(): void {
console.log('ngAfterContentChecked called');
}
ngAfterViewInit(): void {
console.log('ngAfterViewInit called');
}
ngAfterViewChecked(): void {
console.log('ngAfterViewChecked called');
}
ngOnDestroy(): void {
console.log('ngOnDestroy called');
}
}