mcpField
A
angular-lifecycle

angular-lifecycle

github.com/oguzhan18开发7176 次安装31 周前更新
代码仓库

关于 angular-lifecycle

面向 Angular 21 开发者的生命周期钩子参考技能,介绍组件中各钩子的选择及常见用法,涵盖初始化、变更处理和清理。

主要功能

  1. 01初始化与清理建议
  2. 02处理输入变更
  3. 03视图与投影内容钩子
  4. 04自定义变更检测
  5. 05结合 OnPush 使用生命周期钩子

适用场景

  1. 01选择组件初始化钩子
  2. 02响应组件输入变化
  3. 03在销毁时清理订阅
  4. 04视图初始化后访问 DOM

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/oguzhan18/angular-ecosystem-skills --skill angular-lifecycle

安装后在 Claude Code 中输入/angular-lifecycle确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/discussions/
_INDEX.md
references/docs/
_INDEX.md
references/issues/
_INDEX.md
references/releases/
_INDEX.md

详细介绍

Angular 生命周期钩子

版本: Angular 21(2025) 标签: 生命周期、钩子、ngOnInit、ngOnChanges

参考: 生命周期钩子 • API

最佳实践

  • 使用 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