※現在この方法は推奨されません
前回はES5で簡単なAngular v2のサンプルプログラムを書きました。
今回はAngularJSの特徴でもあった「双方向バインディング」をやってみましょう。
メインのHTMLは前回とあまり変わりません。
app.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.17/Rx.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.17/angular2-polyfills.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.17/angular2-all.umd.dev.js"></script>
<script src="components/hello-component/hello-component.js"></script>
</head>
<body>
<hello-component></hello-component>
</body>
</html>
※ app.jsは今回は使わないため空でもOKです。
app.js
'use strict';
(function() {
})();
まずはJavaScriptから。templateに直書きするとコードが汚れるのでtemplateUrlを使います。
components/hello-component/hello-component.js
(function(app) {
app.HelloComponent = ng.core
.Component({
selector: 'hello-component'
})
.View({
templateUrl: 'components/hello-component/hello-component.template.html'
})
.Class({
constructor: function() {
this.name = 'world';
}
});
document.addEventListener('DOMContentLoaded', function() {
ng.platform.browser.bootstrap(app.HelloComponent);
});
})(window.app || (window.app = {}));
テンプレートHTMLの中身はこのようになっています。
components/hello-component/hello-component.template.html
<p>Hello, {{name}} !</p>
<input type="text" [(ngModel)]="name" />
Angular v2では、[(ngModel)]="変数名" と書くと関連付けられた変数(今回はthis.name)が双方向バインディングされます。
ちなみに、[ngModel]="変数名" と書くと単方向バインディングとなり、inputの初期値は入りますが、文字を入力しても画面に反映されなくなります。
今回のサンプルはCodepenでも公開しております。
https://codepen.io/puku0x/pen/zqQNea
まとめ
Angular v2の記法を用いて、双方向バインディングができました。
v1.x系と比べてかなり独特な書き方なので、最初は混乱するかもしれませんが頑張って慣れましょう。
次回は繰り返し処理をやります。