iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 16
2
自我挑戰組

Angular2學習筆記系列 第 16

Lifecycle Hooks 學習筆記 (一)

  • 分享至 

  • xImage
  •  

請搭配官網原文:LIFECYCLE HOOKS

Component lifecycle hooks

每個Component都有一個被Angular所管理的LifeCyle

Angular提供一系列的lifecycle hooks 如下圖

這些Lifecycle hooks,讓我們在關鍵的生命週期時刻 (例如:初始化使用ngOnInit)

處理相對應的相關操作 (例如:在初始化時設定資料初值)。

Directive是「沒有Component Content及View的【Component】」,

移除上圖藍底標示區塊,其他都跟Component一樣。

在Component中操作Lifecycle hooks步驟如下

  • 標示Component要實作哪個Lifecyle hook interface
// in my-component.ts
export class MyComponent implements OnInit {
	...
}
  • 從Angular核心函式庫,import Lifecyle hook interface
// in my-component.ts
import { OnInit} from '@angular/core';
  • 實作Lifecyle hook interface規定要實作的方法
// in my-component.ts
ngOnInit {
	console.log("Component Init");
}

一個簡單的元件使用ngOnInit設定初值的範例如下所示

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

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss'],
})
export class TestComponent implements OnInit {

  title:string;

  constructor(){}

  ngOnInit() { 
  	this.title = 'test title';
  }

}

Lifecycle sequence

Angular會按照下面的順序在特定的時刻使用這些Lifecyle hoooks。

Hooks 目的 時機
ngOnChanges Component或Directive綁定的input property發生變化時,此方法會接收一個具有當前值及先前值的SimpleChanges類別的物件可供操作 在ngOnint前會呼叫一次,或者是一個或多個綁定的input property發生變化時
ngOnInit 初始化Component或Directive 在首次ngOnChanges完成之後觸發,只會發生一次
ngDoCheck 檢測Component或Directive的變化 在每個Angular檢測變化的周期中呼叫,最快會發生在首次ngOnChanges和ngOnInit之後
ngAfterContentInit 只用在Component,把ng-content的內容投射至Component的View之後呼叫 在首次ngDoCheck後發生,只呼叫一次
ngAfterContentChecked 只用在Component,每次完成ng-content的變更檢測之後呼叫 ngAfterContentInit和每次NgDoCheck之後呼叫
ngAfterViewInit 只用在Component,初始化完Component View及Child Component View之後呼叫。 在首次ngAfterContentChecked後發生,且只會呼叫一次
ngAfterViewChecked 只用在Component,每次做完Component View和Child Component的變更檢測之後呼叫 ngAfterViewInit和每次ngAfterContentChecked之後呼叫
ngOnDestroy 在這邊可以取消訂閱Observable及detach Event Handler 在Angular銷毀Component及Directive前呼叫

先看到這邊,下一篇再來看官網提供的範例。


上一篇
Angular2 踩雷系列文(一)
下一篇
Lifecycle Hooks 學習筆記 (二)
系列文
Angular2學習筆記19
.

尚未有邦友留言

立即登入留言