ビール片手にプログラム ~ そうだ!遊ぼう! ~

ただ飲みながら遊んでいる話。まじめなこととかはしません。

Angular.jsのチュートリアルをして遊ぼう ①テンプレート構文

今回はAngular.jsの公式サイトのチュートリアルのテンプレート構文の箇所を実施して遊ぼうと思います。 Angular.jsは1.x時代に少し触っただけなので楽しみです。

1. 今日のお供

久しぶりのビールです! サッポロ 北海道生ビール [ 350ml×24本 ]

2. 今回参考にしたサイト

私はただ備忘録として、遊んだ結果を書きたいだけなので、本気でやりたい方はこちらを参考にされたほうが良いかと思います。

angular.jp

3. 新しいプロジェクトを作成する

ドキュメントの「Click here to create a new project in StackBlitz.」リンクを押下すると、ブラウザでStackBlitzのページが開きます。
このWEB上の環境で開発を進めていく形となります。

f:id:front-end:20190602112651p:plain
StackBlitz

4. テンプレート構文を使用する

すでに定義されているproducts(商品情報)をテンプレート構文を使用して表示できるようにしていきます。
商品情報はproducts.tsに定義されています。

f:id:front-end:20190602115157p:plain
products.ts

(1) product-list.component.htmlを開きます。

f:id:front-end:20190602114632p:plain
product-list.component.html

(2) ngForセレクタを使用し、繰り返し制御をします。

下記をproduct-list.component.htmlに記入すると、商品数分「商品」が表示されます。

<!-- 商品分繰り返す -->
<div *ngFor="let product of products">
  商品
</div>

f:id:front-end:20190602122542p:plain
ngFor

(3) 内挿構文{{}}を使用し、商品名を表示します。

下記をproduct-list.component.htmlに記入すると、商品数分の商品名が表示されます。

<!-- 商品分繰り返す -->
<div *ngFor="let product of products">
  <h3>{{ product.name }}</h3>
</div>

f:id:front-end:20190602122250p:plain
内挿構文{{}}

(4) プロパティバインディング[]を使用し、アンカーのタイトルを表示します。

下記をproduct-list.component.htmlに記入すると、アンカーのタイトルが設定されます。

<!-- 商品分繰り返す -->
<div *ngFor="let product of products">
  <h3>
    <a [title]="product.name + ' details'">
      {{ product.name }}
    </a>
  </h3>
</div>

f:id:front-end:20190602122410p:plain
プロパティバインディング

(5) ngIfセレクタを使用し、商品の説明を表示します。

下記をproduct-list.component.htmlに記入すると、商品説明が設定されている商品のみ、商品の説明が表示されます。

<!-- 商品分繰り返す -->
<div *ngFor="let product of products">
  <h3>
    <a [title]="product.name + ' details'">
      {{ product.name }}
    </a>
  </h3>
  <p *ngIf="product.description">
    Description: {{ product.description }}
  </p>
</div>

f:id:front-end:20190602122451p:plain
ngif

(6) イベントバインディング()を使用し、イベントを紐付けます。

下記をproduct-list.component.htmlに記入すると、clickイベントにproduct-list.component.tsで定義されているshare()イベントが紐付けされます。

<!-- 商品分繰り返す -->
<div *ngFor="let product of products">
  <h3>
    <a [title]="product.name + ' details'">
      {{ product.name }}
    </a>
  </h3>
  <p *ngIf="product.description">
    Description: {{ product.description }}
  </p>
  <button (click)="share()">
    Share
  </button>
</div>

f:id:front-end:20190602122753p:plain
イベントバインディング()

share()イベントの内容

f:id:front-end:20190602122701p:plain
share()イベント

5. テンプレート構文が使えました!

今回はチュートリアルにあるとおり、下記のテンプレート構文を使用しました。

① ngFor
② ngIf
③ 内挿{{}}
④ プロパティバインディング[]
⑤ イベントバインディング()

次回はコンポーネントの作成・使用が出来たらいいなと思います。