Lifecycle hooks 是 Angular 在组件生命周期的特定时刻(创建、输入变化、渲染和销毁)调用的方法。您可以通过在组件类中添加接口方法来实现它们。
按顺序排列的主要钩子
ts
{ , , , , } ;
({ ... })
, , {
() {
}
() {
}
() {
}
}
constructor → DI happens; inputs NOT yet available
ngOnChanges → when @Input values are set/changed
ngOnInit → once, after first ngOnChanges ★ (init, fetch data)
ngDoCheck → every change detection run (custom change detection)
ngAfterContentInit → projected content (<ng-content>) initialized
ngAfterViewInit → the component's view + child views ready ★ (access @ViewChild)
ngAfterViewChecked → after each view check
ngOnDestroy → before removal ★ (unsubscribe, clear timers)
ngOnInit() {
this.userService.getUsers().subscribe(u => this.users = u); // init/fetch — inputs are ready
}
ngAfterViewInit() {
this.chart.nativeElement.focus(); // the DOM/@ViewChild exists now
}
ngOnDestroy() {
this.subscription.unsubscribe(); // prevent memory leaks!
clearInterval(this.timer);
}
ngOnInit — 初始化和数据获取的标准位置(与构造函数不同,@Input 在这里可用)。ngAfterViewInit — 当子视图和 @ViewChild 引用存在时。ngOnDestroy — 清理:取消订阅 Observables、清除计时器、移除监听器。构造函数只应进行 DI;输入在那里还未绑定。ngOnInit 在 Angular 设置好组件及其输入后运行 — 这是启动逻辑的正确位置。
Lifecycle hooks 让你在正确的时刻运行逻辑 — 在 ngOnInit 中初始化,在 ngAfterViewInit 中访问渲染的视图,最关键的是在 ngOnDestroy 中清理(取消订阅 Observables 是 Angular 中避免内存泄漏的 #1 方法)。
了解每个钩子的顺序和作用对于正确的数据获取、DOM 访问和资源管理至关重要。