Week 07 · Day 01 — 元件生命週期:概論

學習目標

  • 認識生命週期鉤子(Lifecycle Hooks)
  • 了解各鉤子的執行時機與順序
  • 明白該在哪裡做初始化、在哪裡清理

重點

生命週期鉤子 - Angular 在元件的不同階段會呼叫特定方法 - 用 implements 這些介面來掛鉤 - 最常用:OnInit / OnDestroy / OnChanges / AfterViewInit

執行順序(一次載入)

import { Component, OnInit,
         OnDestroy, OnChanges,
         AfterContentInit, AfterViewInit,
         SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-lifecycle',
  template: `<p>{{ message }}</p>`
})
export class LifecycleComponent
  implements OnInit, OnDestroy, OnChanges,
             AfterContentInit, AfterViewInit {

  message: string = "";

  constructor() {
    console.log('1. Constructor');     // 建構,還沒初始化屬性輸入
  }

  ngOnInit(): void {
    console.log('2. ngOnInit');        // 第一次綁定後
    this.message = "Component initialized";
  }

  ngOnChanges(changes: SimpleChanges): void {
    console.log('3. ngOnChanges');     // @Input 變化時(也可能是初始化前)
  }

  ngAfterContentInit(): void {
    console.log('4. ngAfterContentInit'); // 內容投影完成
  }

  ngAfterViewInit(): void {
    console.log('5. ngAfterViewInit');    // 視圖完成
  }

  ngOnDestroy(): void {
    console.log('6. ngOnDestroy');     // 元件銷毀,清理資源
  }
}

重點 - constructor 最先但別做重初始化(此時輸入還沒好) - ngOnInit:做初始化最好時機 - ngOnDestroy:清訂閱、計時器等

實作

  1. 建立含上述所有鉤子的元件
  2. 在 console 觀察輸出順序
  3. 配合路由切到別頁,觀察 ngOnDestroy

作業

  • 掛上所有生命週期鉤子並觀察順序
  • 說出 ngOnInit 的用途
  • 說出 ngOnDestroy 的用途