LoginSignup
45
32

More than 5 years have passed since last update.

Angular の ngOninitの必要性 ~なぜconstructorではダメなのか~

Posted at

Angularとは

「Angular(アンギュラー)」は、Googleによって開発されているJavaScriptフレームワークです。
アプリケーションを作成する時、ページをクリックしたときに発火させたいイベントが多々あります。それを実現させたいとき、ngOninitが必要となります。(constructorではできない)

constructorとは

Typescript,Javascriptに付随するものである
Classの初期化時に発火する

class Hoge {
    id: number
    constructor(num: number) { 
        this.id = num;
    }
}
let h = new Hoge(1)
console.log(h.id)
==> 1

ngOnInitとは

Angularに付随するものである。
Lifecycleの一部
Lifecycleとは、ディレクティブやコンポーネントが変化するタイミングで、コールバックを設定できる仕組みである。

つまり、AngularのLifeCycleに乗っ取った処理をすることができるのである。
下記で使用しているのは、AngularのLifeCycleの一つのngOnInitである。(Componentの初期化時に発火する)

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

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

  constructor(
  ) {
   console.log('constructor');
  }

  ngOnInit() {
    console.log('ngOnInit');
  }
}
===> 'constructor'
===> 'ngOnInit'

まとめ

Angularでは、constructorは、component作成途中で実行されます。
ngOnInitはcomponent作成後に呼び出されます。
したがって、アプリケーションを作成する時、ページをクリックしたときにイベントを発火させたいというようなUIUX観点から見た要件は、ngOnInit(LyfeCycle)を使用することで簡単に実現することができるのです。

参考

45
32
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
45
32