关于 angular-lifecycle
面向 Angular 21 开发者的生命周期钩子参考技能,介绍组件中各钩子的选择及常见用法,涵盖初始化、变更处理和清理。
主要功能
- 01初始化与清理建议
- 02处理输入变更
- 03视图与投影内容钩子
- 04自定义变更检测
- 05结合 OnPush 使用生命周期钩子
适用场景
- 01选择组件初始化钩子
- 02响应组件输入变化
- 03在销毁时清理订阅
- 04视图初始化后访问 DOM
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ oguzhan18/ angular-ecosystem-skills --skill angular-lifecycle安装后在 Claude Code 中输入/angular-lifecycle确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/discussions/_INDEX.mdreferences/docs/_INDEX.mdreferences/issues/_INDEX.mdreferences/releases/_INDEX.md详细介绍
Angular 生命周期钩子
版本: Angular 21(2025) 标签: 生命周期、钩子、ngOnInit、ngOnChanges
最佳实践
- 使用 OnInit 进行初始化
import { OnInit } from '@angular/core';
@Component({})
export class MyComponent implements OnInit {
ngOnInit() {
// Initialize data, call services
this.loadData();
}
}
- 使用 OnDestroy 进行清理
import { OnDestroy } from '@angular/core';
@Component({})
export class MyComponent implements OnDestroy {
private destroy$ = new Subject<void>();
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
}
- 使用 OnChanges 处理输入变更
import { OnChanges, SimpleChanges } from '@angular/core';
@Component({})
export class MyComponent implements OnChanges {
@Input() data: any;
ngOnChanges(changes: SimpleChanges) {
if (changes['data']) {
console.log('Data changed:', this.data);
}
}
}
- 使用 AfterViewInit 操作 DOM
import { AfterViewInit, ViewChild, ElementRef } from '@angular/core';
@Component({})
export class MyComponent implements AfterViewInit {
@ViewChild('el') el!: ElementRef;
ngAfterViewInit() {
this.el.nativeElement.focus();
}
}
- 使用 AfterContentInit 处理投影内容
import { AfterContentInit, ContentChild } from '@angular/core';
@Component({})
export class MyComponent implements AfterContentInit {
@ContentChild('header') header!: ElementRef;
ngAfterContentInit() {
// Access projected content
}
}
- 使用 DoCheck 进行自定义变更检测
import { DoCheck } from '@angular/core';
@Component({})
export class MyComponent implements DoCheck {
ngDoCheck() {
// Custom change detection
}
}
- 在生命周期中使用 OnPush
@Component({
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {
@Input() data: any;
ngOnChanges(changes: SimpleChanges) {
// OnPush needs explicit change detection trigger
}
}
- 了解 constructor 与 ngOnInit 的区别
// Constructor - for dependency injection only
constructor(private service: MyService) {}
// ngOnInit - for initialization logic
ngOnInit() {
this.data = this.service.getData();
}
评论
支持 Markdown