0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Angular】Angularって何だろう(画面表示タイミングに関わるTypeScript編:ngOnInit・ngOnChanges・ngOnDestroy)

0
Posted at

1.はじめに

最近近所の鰻屋さんで鰻を食べました。
今回は、第四弾でAngularの基本的な操作のうちライフサイクルフックについてまとめていきます。
Angularでは、コンポーネントの生成から破棄までの流れの中で、特定のタイミングに自動で実行される処理をライフサイクルフックと呼びます。

2.基本的な書き方

概要

Angular では、コンポーネントは以下のように構成されます。
htmlファイル・tsファイル・cssファイルの3ファイル構成になります。

app.component.html

<h1 [ngClass]="titleClass">{{ value }}</h1>
<button (click)="pushButton()">
  ボタンを押してください
</button>

app.component.ts

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

@Component({
  selector: 'app-root', // HTMLタグの名前
  templateUrl: './app.component.html', // HTMLテンプレート
  styleUrls: ['./app.component.css'] // スタイルシート
})

// 今回はここに書くことをまとめていきます。
export class AppComponent {
  value: string = '';
  titleClass: string = 'title';

  // ボタンをクリックしたときの処理
  pushButton() {
    this.value = 'ボタンが押されました!';
  }
}

app.component.css

.title {
  color: red;
}

今回は下記の概念についてまとめていきます。

項目 説明
ngOnInit コンポーネント初期化時に実行
ngOnChanges @Inputの値変更時に実行
ngOnDestroy コンポーネント破棄時に実行

3.解説

①ngOnInit

ngOnInitとは、コンポーネントの初期化が完了したタイミングで一度だけ実行される処理です。
画面表示時のデータ取得や初期設定などを行う場合によく利用します。

<基本的な書き方>

ngOnInit() {
  // 初期化処理
}

<テストコード>

sample.component.ts

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

@Component({
  selector: 'app-sample',
  templateUrl: './sample.component.html'
})
export class SampleComponent implements OnInit {

  message = '';

  ngOnInit() {
    this.message = 'ngOnInitで初期化しました';
  }

}

sample.component.html

<h2>{{ message }}</h2>

画面表示時に ngOnInit が実行されるため、

ngOnInitで初期化しました

と表示されます。
image.png

🔍Vueとの違い
Vueのcreated()に近い役割です。
こちらもデータの初期化やAPI呼び出しを行う場合によく利用されます。


②ngOnChanges

ngOnChangesとは、親コンポーネントから受け取った値(@Input)が変更された際に実行される処理です。
値の変更前後を取得できるため、変更内容に応じて処理を行いたい場合に利用します。

<基本的な書き方>

ngOnChanges(changes: SimpleChanges) {
}

<テストコード>

child.component.ts

import {
  Component,
  Input,
  OnChanges,
  SimpleChanges
} from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html'
})
export class ChildComponent implements OnChanges {

  @Input()  userName: string = '';
  log: string = '';

  ngOnChanges(changes: SimpleChanges) {

    const previous =
      changes.userName.previousValue;

    const current =
      changes.userName.currentValue;

    this.log =
      `変更:${previous}${current}`;
  }
}

child.component.html

<p>{{ log }}</p>

parent.component.html

<app-child
  [userName]="name">
</app-child>

親コンポーネント側で name の値が変更されると、

変更:山田 → 鈴木

のように表示されます。

image.png

🔍Vueとの違い

Vueのwatch()に近い機能です。
ただし、Angularの ngOnChanges は @Input の変更のみを監視します。


③ngOnDestroy

ngOnDestroyとは、コンポーネントが画面から削除される直前に一度だけ実行される処理です。
タイマーやAPI監視などの後片付けによく利用します。

<基本的な書き方>

ngOnDestroy() {
  // 終了処理
}

<テストコード>

child.component.ts

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html'
})
export class SampleComponent
implements OnInit, OnDestroy {

  count = 0;

  intervalId: any;

  ngOnInit() {

    this.intervalId = setInterval(() => { this.count++; }, 1000);}

  ngOnDestroy() {
    clearInterval(this.intervalId);
    console.log('タイマーを停止しました');
  }
}

child.component.html

<h2>現在のカウント:{{ count }}</h2>

parent.component.ts

export class AppComponent {

  show = true;

  toggle() {
    this.show = !this.show;
  }
}

parent.component.html

<button (click)="toggle()">
  表示切替
</button>

<app-child *ngIf="show"></app-child>

コンポーネント表示中は1秒ごとにカウントアップします。
コンポーネントが削除される際に ngOnDestroy が呼ばれ、タイマーが停止します。

image.png

🔍なぜ必要?

ngOnDestroy を利用せずにタイマーや購読処理を残したままにすると、不要な処理が動き続けてしまいます。

そのため Angular では後片付けを行うための重要なライフサイクルフックとなっています。


4.さいごに

今回は Angular のライフサイクルフックとして、

  • ngOnInit
  • ngOnChanges
  • ngOnDestroy

を紹介しました。

ライフサイクルフックを利用することで、コンポーネントの生成から破棄までのタイミングに応じた処理を実装できます。

次回は Angular のCSS編として、コンポーネントCSSや ngClass、ngStyle についてまとめていきたいと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?