iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 15
1
Modern Web

Angular 8 從推坑到放棄系列 第 15

[Day 14] 了解 Angular Component 生命週期

了解 Angular Component 生命週期

在使用Angular Component時,可以在程式中針對 Angular 在運作程式時放入不同的 lifecycle hooks,來在不同的行為中做出更深入的處理

  • ngOnChanges - 每當 @Input() 的值有變化時,都會呼叫此方法,藉此得知資料被改變了,如下程式:
import { Component, Input, OnChanges, OnInit } from '@angular/core';

@Component({
  selector: 'app-value',
  template: `<span>{{ value }}</span>`
})
export class ValueComponent implements OnInit, OnChanges {
  @Input() value;

  ngOnInit() {
    console.log('App Component Init');
  }

  ngOnChanges() {
    console.log('Value Component Input Changed');
  }
}

@Component({
  selector: 'my-app',
  template: `
  <app-value [value]="value"></app-value>
  `
})
export class AppComponent  {
  value = 100;
}
  • ngOnInit - after the first ngOnChanges

在第一次執行完 ngOnChanges() 後(如果有的話),就會進入 ngOnInit() 週期

但在TypeScript或ES6中還存在名為 constructor 的建構式,開發過程中經常會混淆二者,畢竟它們的含義有某些重複部分,那ngOnInit和constructor之間有什麼區別呢?它們各自的適用場景又是什麼呢?

最主要的區別是 constructor 的自身屬性,並不屬於Angular的範疇,所以Angular沒有辦法控制 constructor , constructor會在類生成例項時呼叫

import {Component} from '@angular/core';
@Component({
selector: 'hello-world',
templateUrl: 'hello-world.html'
})
export class HelloWorldComponent {

constructor() {
    console.log('constructor被呼叫,但和Angular無關');
}

}
// 生成類例項,此時會呼叫constructor
new HelloWorld();

Angular無法控制constructor,因此建議大部分的初始化程式都建議在 ngOnInit() 週期中執行,而非在建構式(constructor)處理,尤其是比較複雜程式或 ajax 呼叫,建議都在 ngOnInit() 中執行,

在建構式(constructor)中明顯的缺點是:撰寫單元測試時,由於建構式本身對外部程式的依賴太重,容易造成測試程式難以撰寫。

  • ngDoCheck - after every run of change detection
  • ngAfterContentInit - after component content initialized
  • ngAfterContentChecked - after every check of component content
  • ngAfterViewInit - after component's view(s) are - initialized
  • ngAfterViewChecked - after every check of a component's view(s)
  • ngOnDestroy - just before the component is destroyed

參考

  1. Lifecycle Hooks
  2. 詳解Angular之constructor和ngOnInit差異及適用場景

上一篇
[Day13]使用 Angular Local Reference 取得資料
下一篇
[Day 15] Day 15 了 深入了解 Directive
系列文
Angular 8 從推坑到放棄30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言