LoginSignup
0
1

More than 3 years have passed since last update.

ES5で書くAngular v2(3)「繰り返し処理」

Last updated at Posted at 2016-05-17

※現在この方法は推奨されません

前回はAngular v2の双方向バインディングを試しました。

今回はAngular v2公式サイトのTypeScriptサンプルを参考に繰り返し処理をしてみましょう。

メインのHTMLにlist-componentを追加します。

index.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/list-component/list-component.js"></script>
    </head>
    <body>
        <list-component></list-component>
    </body>
</html>

コンポーネントのJavaScriptに配列heroesを追加します。

components/list-component/list-component.js
(function(app) {
    app.ListComponent = ng.core
    .Component({
        selector: 'list-component'
    })
    .View({
        templateUrl: 'components/list-component/list-component.template.html'
    })
    .Class({
        constructor: function() {
            this.heroes = ["Mr. Nice",
                           "Narco",
                           "Bombasto",
                           "Celeritas",
                           "Magneta",
                           "RubberMan",
                           "Dynama",
                           "Dr IQ",
                           "Magma",
                           "Tornado"
                          ];
        }
    });
    document.addEventListener('DOMContentLoaded', function() {
        ng.platform.browser.bootstrap(app.ListComponent);
    });
})(window.app || (window.app = {}));

テンプレートにはngForを使った繰り返し処理を書きます。

components/list-component/list-component.template.html
<li *ngFor="let hero of heroes">
    {{hero}}
</li>

↓今回の動くサンプルはこちらです。
https://codepen.io/puku0x/pen/ZWNLgx

ngForの前の*<li>要素(とその子要素)をテンプレートにするという意味だそうです。
letが見慣れない方はvarに置き換えると良いでしょう。

まとめ

Angular v2のngForを用いて1.x系にあった

AngularJS v1.xを用いた場合
<li ng-repeat="hero in $ctrl.heroes track by $index">
    {{hero}}
</li>

といった繰り返し処理を行いました。

個人的には「文字列配列の場合はtrack by必須」という縛りが無くなって嬉しいのですが、皆さんはいかがでしょうか?

次回はクリックイベントをやってみようと思います。

0
1
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
1