君は心理学者なのか?

大学時代に心理学を専攻しなぜかプログラマになった、サイコ(心理学)プログラマかろてんの雑記。

angular2で要素をclickした時に、処理を行う

angular2で簡単にクリックイベントを実装

angularJSではng-clickというディレクティブを使ってクリックイベントを実装していました。

angular2ではどのように実装するか、実際に実装しつつ試してみたいとおもいます。

手順

  1. 準備
  2. app.component.htmlにクリックさせたい要素を配置
  3. app.component.tsにクリックしたときの処理を記述

準備

新規プロジェクトを作成し、サーバをスタートさせます。

ng new click-event
ng serve

 

app.component.htmlにクリックさせたい要素を配置

// app.component.html
<h1 (click)="countUp()">クリックしてね</h1>

app.component.tsにクリックしたときの処理を記述

// app.component.ts
export class AppComponent {
  count :number = 0;
  countUp() :void {
    this.count ++;
    console.log(this.count + '回クリックされたよ');
  }
}

結果f:id:karoten512:20170831233229g:plain