Angular2でイベントバインディングを使ってイベントを処理する方法をまとめました。
※Angular2の2.0.0版、TypeScriptを使って確認したものです。(デモはv4.4.3、v2.0.0で動作確認)
※目次をクリックすると目次の下部にコンテンツが表示されます。
イベントバインディング
●構文
(event) = “handler”
例1)$event変数を使用
・テンプレート
<input (keyup)=”onKey($event)”>
・コンポーネント
values=”;
onKey(event:any) {
this.values += event.target.value;
}
・”keyup”イベントが発生するとコンポーネントの”onKey”メソッドをコール。
・イベントが発生すると、コンポーネントに渡された”$event”変数を介してアクセスする事ができる。
・$event.targetによってHTMLInputElementにアクセスし、value属性のデータを取得できる。
例2)テンプレートリファレンス変数(template reference variable)を使用
・テンプレート
<input #box (keyup)=”onKey(box.value)”>
・コンポーネント
values=”;
onKey(value:string) {
this.values += value;
}
・変数名の前に”#”付与してテンプレートリファレンス変数を定義する。
・この変数を使って直接要素にアクセスできる。
(event) = “handler”
例1)$event変数を使用
・テンプレート
<input (keyup)=”onKey($event)”>
・コンポーネント
values=”;
onKey(event:any) {
this.values += event.target.value;
}
・”keyup”イベントが発生するとコンポーネントの”onKey”メソッドをコール。
・イベントが発生すると、コンポーネントに渡された”$event”変数を介してアクセスする事ができる。
・$event.targetによってHTMLInputElementにアクセスし、value属性のデータを取得できる。
例2)テンプレートリファレンス変数(template reference variable)を使用
・テンプレート
<input #box (keyup)=”onKey(box.value)”>
・コンポーネント
values=”;
onKey(value:string) {
this.values += value;
}
・変数名の前に”#”付与してテンプレートリファレンス変数を定義する。
・この変数を使って直接要素にアクセスできる。
マウスイベントに応じてボタンの色を変えるサンプル
1)シンプルな使用例
下記例では、ボタンをクリックするとイベントバインディングを使って”btnColor1″という変数に’btn-success’というBootstrap3のCSSクラス名を設定しています。
(click)=”btnColor1=’btn-success'”
“btnColor1″という変数は、NgClassディレクティブを使ってボタンのCSSを設定しているので、クリックするとボタンの色が変わります。他のイベントについても同様です。
下記例では、ボタンをクリックするとイベントバインディングを使って”btnColor1″という変数に’btn-success’というBootstrap3のCSSクラス名を設定しています。
(click)=”btnColor1=’btn-success'”
“btnColor1″という変数は、NgClassディレクティブを使ってボタンのCSSを設定しているので、クリックするとボタンの色が変わります。他のイベントについても同様です。
<button class="btn" [ngClass]="btnColor1" (click)="btnColor1='btn-success'" (mouseenter)="btnColor1='btn-primary'" (mouseleave)="btnColor1='btn-defult'">イベント処理</button>
2)$event変数を使った例
下記例では、$event変数を使ってイベントのタイプを取得し、イベントのタイプ毎に処理を切替えています。
(テンプレート)
<button class="btn" [ngClass]="btnColor2"
(click)="handleEvent($event)"
(mouseenter)="handleEvent($event)"
(mouseleave)="handleEvent($event)">イベント処理2</button>
(コンポーネントクラス)
public btnColor2 = '';
handleEvent(event:any) {
console.log("イベントのタイプ: " + event.type);
switch (event.type){
case "mouseover":
this.btnColor2 = "btn-primary";
break;
case "mouseenter":
this.btnColor2 = "btn-primary";
break;
case "click":
this.btnColor2 = "btn-success";
break;
default:
this.btnColor2 = "btn-default";
break;
}
}
ラジオボタンに使用したサンプル
1)$event変数を使った例
<label> <input type="radio" value="red" (change)="color1=$event.target.value" [checked]="color1=='red'"> Red </label>
①(change)=”color1=$event.target.value”
・イベントバインディング
・ユーザーのチェック動作を”change”イベントで検知し、$event変数を介して値を取得して”color1″変数に保持。
②[checked]=”color1==’red'”
・プロパティバインディング
・”color1変数が”red”の場合は、”checked”属性をtrueにする。
2)ローカルテンプレート変数を使った例
<label> <input #clr1 type="radio" value="red" (change)="color2=clr1.value" [checked]="color2=='red'"> Red </label>
①#clr1
・ローカルテンプレート変数を定義
②(change)=”color2=clr1.value”
・イベントバインディング
・ユーザーのチェック動作を”change”イベントで検知し、ローカルテンプレート変数を介して値を取得して”color2″変数に保持。
③[checked]=”color2==’red'”
・プロパティバインディング
・”color2変数が”red”の場合は、”checked”属性をtrueにする。
デモ
Angular : 4.4.3(2.0.0でも動作確認済み)
Bootstrap : 3.x
関連記事の目次
Bootstrap : 3.x
<html>
<head>
<title>Angular 2 Demo</title>
<script src="https://npmcdn.com/core-js/client/shim.min.js"></script>
<script src="https://unpkg.com/zone.js@0.7.4?main=browser"></script>
<script src="https://npmcdn.com/systemjs@0.19.39/dist/system.src.js"></script>
<script src="./js/systemjs.config.js"></script>
<script>
System.import('./ts/app.ts').catch(function(err){ console.error(err); }); </script>
<link rel="stylesheet" href="./css/bootstrap.min.css">
<link rel="stylesheet" href="./css/styles.css">
</head>
<body>
<div class="container">
<my-app>Loading...</my-app>
</div>
</body>
</html>
(systemjs.config.js)
(function (global) {
var ngVer = '@4.4.3';
System.config({
transpiler: 'ts',
typescriptOptions: {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es2015", "dom"],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"strict": true
},
meta: {
'typescript': {
"exports": "ts"
}
},
paths: {
'npm:': 'https://unpkg.com/'
},
map: {
'app': 'app',
'@angular/animations': 'npm:@angular/animations' + ngVer + '/bundles/animations.umd.js',
'@angular/animations/browser': 'npm:@angular/animations' + ngVer + '/bundles/animations-browser.umd.js',
'@angular/core': 'npm:@angular/core' + ngVer + '/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common' + ngVer + '/bundles/common.umd.js',
'@angular/common/http': 'npm:@angular/common' + ngVer + '/bundles/common-http.umd.js',
'@angular/compiler': 'npm:@angular/compiler' + ngVer + '/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser' + ngVer + '/bundles/platform-browser.umd.js',
'@angular/platform-browser/animations': 'npm:@angular/platform-browser' + ngVer + '/bundles/platform-browser-animations.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic' + ngVer + '/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http' + ngVer + '/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router' + ngVer + '/bundles/router.umd.js',
'@angular/router/upgrade': 'npm:@angular/router' + ngVer + '/bundles/router-upgrade.umd.js',
'@angular/forms': 'npm:@angular/forms' + ngVer + '/bundles/forms.umd.js',
'@angular/upgrade': 'npm:@angular/upgrade' + ngVer + '/bundles/upgrade.umd.js',
'@angular/upgrade/static': 'npm:@angular/upgrade' + ngVer + '/bundles/upgrade-static.umd.js',
// other libraries
'rxjs': 'npm:rxjs@5.0.1',
'tslib': 'npm:tslib/tslib.js',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
'ts': 'npm:plugin-typescript@5.2.7/lib/plugin.js',
'typescript': 'npm:typescript@2.3.2/lib/typescript.js',
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.ts',
defaultExtension: 'ts',
meta: {
'./*.ts': {
loader: 'systemjs-angular-loader.js'
}
}
},
rxjs: {
defaultExtension: 'js'
}
}
});
})(this);
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'my-app',
template:`
<strong>1)マウスイベントを使ってボタンの色を変更</strong>
<p>ボタンにマウスを合わせる、離す、クリックすると色が変わります。</p>
<button class="btn" [ngClass]="btnColor1" (click)="btnColor1='btn-success'" (mouseenter)="btnColor1='btn-primary'" (mouseleave)="btnColor1='btn-defult'">イベント処理</button> <button class="btn" [ngClass]="btnColor2" (click)="handleEvent($event)" (mouseenter)="handleEvent($event)" (mouseleave)="handleEvent($event)">イベント処理2</button><br />
<br />
<strong>2)ラジオボタン($eventオブジェクトを使用)</strong>
<form>
<label>
<input type="radio" value="red"
(change)="color1=$event.target.value" [checked]="color1=='red'">
Red
</label><br/>
<label>
<input type="radio" value="green"
(change)="color1=$event.target.value" [checked]="color1=='green'">
Green
</label><br/>
<label>
<input type="radio" value="blue"
(change)="color1=$event.target.value" [checked]="color1=='blue'">
Blue
</label><br/>
<span>color1 = {{color1}}</span><br/>
</form>
<br />
<strong>3)ラジオボタン(ローカルテンプレート変数を使用)</strong>
<form>
<label>
<input #clr1 type="radio" value="red"
(change)="color2=clr1.value" [checked]="color2=='red'">
Red
</label><br/>
<label>
<input #clr2 type="radio" value="green"
(change)="color2=clr2.value" [checked]="color2=='green'">
Green
</label><br/>
<label>
<input #clr3 type="radio" value="blue"
(change)="color2=clr3.value" [checked]="color2=='blue'">
Blue
</label><br/>
<span>color2 = {{color2}}</span><br/>
</form>
`
})
export class AppComponent {
public color1 = 'red';
public color2 = 'red';
public btnColor2 = '';
handleEvent(event:any) {
console.log("イベントのタイプ: " + event.type);
switch (event.type){
case "mouseover":
this.btnColor2 = "btn-primary";
break;
case "mouseenter":
this.btnColor2 = "btn-primary";
break;
case "click":
this.btnColor2 = "btn-success";
break;
default:
this.btnColor2 = "btn-default";
break;
}
}
}
@NgModule({
imports: [
BrowserModule,
FormsModule
],
declarations: [
AppComponent
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
platformBrowserDynamic().bootstrapModule(AppModule);