【AngularJS】データバインドでコンポーネントの値をHTMLビューに反映

AngularJSにおけるデータバインドでコンポーネントの値をHTMLビューに反映させる方法についてまとめました。

## 【Interpolation】{{式}}

データバインドとは、「コンポーネントの値」と「HTMLテンプレート(ビュー)」を結び付ける機能です。
つまり、コンポーネントの値をビューに反映させることができます。
データバインドの記法の中で最も代表的なものはInterpolation({{…}})と呼ばれるものです。

■src/app/app.component.ts

import { Component } from '@angular/core';

// コンポーネントの構成情報を定義するデコレータ
@Component({
  // コンポーネントの適用先を表すセレクター式
  selector: 'app-root',


  // コンポーネントに適用するスタイルシート
  styleUrls: ['./app.component.css'],

  // コンポーネントに適用するテンプレート(外部ファイルから読み込み)
    templateUrl: './app.component.html', // アプリケーションルートからの相対パスで指定
})
export class AppComponent {
  title = 'sample';
  contents = 'エクスカリバー';
}

■app/app.component.html

<h1>{{title}}</h1>
<h2>{{contents}}</h2>

## 【Property Binding】[プロパティ名] = “式”

Property Binding([…])では、要素のプロパティを操作できます。

書式

[プロパティ名] = "式"

■src/app/app.component.ts

import { Component } from '@angular/core';

// コンポーネントの構成情報を定義するデコレータ
@Component({
  // コンポーネントの適用先を表すセレクター式
  selector: 'app-root',


  // コンポーネントに適用するスタイルシート
  styleUrls: ['./app.component.css'],

  // コンポーネントに適用するテンプレート(外部ファイルから読み込み)
    templateUrl: './app.component.html', // アプリケーションルートからの相対パスで指定
})
export class AppComponent {
  title = 'sample';
  content = 'トップページに戻る';
  url = 'https://algorithm.joho.info/';
}

■app/app.component.html

<h1>{{title}}</h1>
<a [href]="url">{{contents}}</a>

【補足】Interpolationでも次のように記述できます

<a href="{{url}}">{{contents}}</a>

## 【Attribute Binding】[attr.属性名] = “式”

参考文献・関連記事
参考 【AngularJS入門】基礎とサンプル集
関連 【Ionic入門】Android・iPhoneアプリ開発編
Javascript
スポンサーリンク
西住工房

コメント