Angular 组件生命周期概述

在 Angular 中,组件的生命周期是非常重要的概念。它涉及组件从创建到销毁的整个过程。了解组件的生命周期可以帮助开发者更好地控制组件的行为和性能。

组件生命周期方法

Angular 提供了一系列的生命周期方法,以下是一些常见的生命周期方法:

  • ngOnInit(): 在组件初始化时调用。
  • ngOnChanges(): 在组件输入属性发生变化时调用。
  • ngDoCheck(): 在检测到组件的输入属性、输出属性或内容发生变化时调用。
  • ngOnDestroy(): 在组件被销毁之前调用。

示例代码

以下是一个简单的组件示例,演示了如何使用生命周期方法:

import { Component } from '@angular/core';

@Component({
  selector: 'app-lifecycle-example',
  template: `<h1>Angular Lifecycle Example</h1>`,
})
export class LifecycleExampleComponent {
  constructor() {
    console.log('Lifecycle: constructor');
  }

  ngOnInit() {
    console.log('Lifecycle: ngOnInit');
  }

  ngOnChanges(changes: SimpleChanges) {
    console.log('Lifecycle: ngOnChanges');
  }

  ngDoCheck() {
    console.log('Lifecycle: ngDoCheck');
  }

  ngOnDestroy() {
    console.log('Lifecycle: ngOnDestroy');
  }
}

扩展阅读

要深入了解 Angular 组件生命周期,您可以阅读官方文档:Angular Component Lifecycle

Angular Component Lifecycle