Angular2のプロパティバインディングとアトリビュートバインディング

Angular2のプロパティバインディングとアトリビュートバインディングについてまとめました。
※Angular2の2.0.0版、TypeScriptを使って確認したものです。(デモはv4.4.3、v2.0.0で動作確認)

※目次をクリックすると目次の下部にコンテンツが表示されます。

プロパティバインディング
・コンポーネント内で定義したプロパティの値などをDOM要素のプロパティにセットする。
 
●構文
 
プロパティ名を角括弧でラップするか、”bind-“をプレフィックスする。
 
例)img要素のsrc属性にコンポーネントで定義した値をセット
<img [src]=”ImagePath”>
<img bind-src=”ImagePath”>
 
●サンプル
 

@Component({
  selector: 'my-app',
  template: `
    <p>画像のパスは、{{getPath()}} です。</p>
    <img [src]="sampleImagePath">
    <img bind-src="sampleImagePath">
    <img src="{{sampleImagePath}}">
    <img [src]="getPath()">
  `
})
export class MyApp {
  public sampleImagePath = "./sample.jpg";
  getPath() {
    return "./sample.jpg";
  }
}

HTMLアトリビュート(attribute)とDOMプロパティ(property)
・アトリビュートはHTMLに記述され定義。プロパティはHTMLから構築されたDOMによって定義。
 
・いくつかのHTMLアトリビュートはプロパティと1:1でマッピングされる(idなど)が、あるHTMLアトリビュートは対応するプロパティがない(colspanなど)。
 
・あるDOMプロパティは対応するHTMLアトリビュートがない(textContentなど)。
 
・DOMプロパティは、初期値から変更された場合、現在の値がプロパティの値になるが、HTMLアトリビュートの場合は初期値のまま。
 
例)
<input type=”text” value=”名前”>
ユーザーが”鈴木”と入力し変更した場合。
 DOM要素の”value”プロパティの値は、”鈴木”。
 HTMLの”value”アトリビュートの値は、”名前”。
 input.getAttribute(‘value’) //”名前”がリターン。

アトリビュートバインディング
・aria、svg、tableのspanアトリビュートは、対応する要素プロパティがない。このような場合に、アトリビュートバインディングを使用する。
 
●構文
 
[attr.アトリビュート名]
 
例)
<tr><td [attr.colspan]=”1 + 1″>One-Two</td></tr>
<button [attr.aria-label]=”actionName”>{{actionName}} with Aria</button>
 
以下のようにプロパティバインディングの形式で指定すると”Can’t bind to ‘colspan’ since it isn’t a known native property”のエラーが発生する。
 
<tr><td colspan=”{{1 + 1}}”>Three-Four</td></tr>

プロパティバインディングを使って有効、無効の切替え
input要素のreadonly、チェックボックスのchecked、option要素のselected、button要素のdisabledは、属性名と値のペアで指定せず、属性名を指定するかしないかで有効、無効を切替えています。
 
Angular1では、ng-disabled、ng-checked、ng-readonly、ng-selectedディレクティブを使って設定していましたが、Angular2ではプロパティバインディングを使って設定します。
 
①ボタンの有効無効を切り替え
 
“checkValue”の値がtrueの場合は”disabled”属性が有効になります。
<button class=”btn btn-success” [disabled]=”checkValue”>ボタン</button>
 
②チェックボックスのチェックを切り替え
 
<input type=”checkbox” [checked]=”checkValue”>最上部チェック有効
 
③読込専用を切り替え
 
<input type=”text” [readonly]=”checkValue” value=”最上部チェックで読込専用”/>
 
④選択、未選択を切り替え
 
<select>
 <option selected>選択肢1</option>
 <option>選択肢2</option>
 <option [selected]=”checkValue”>最上部チェックで有効</option>
</select>

デモ
Angular : 4.4.3(2.0.0でも動作確認済み)
Bootstrap : 3.x

Loading…

<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><input type="checkbox" [(ngModel)]="checkValue">有効、無効を切り替え</strong><br />
 
<strong>1)[disabled] ボタンの有効無効を切り替え</strong>
  <button class="btn btn-success" [disabled]="checkValue">ボタン</button><br />
<strong>2)[checked] チェックボックスのチェックを切り替え</strong>
  <input type="checkbox" [checked]="checkValue">最上部チェック有効<br />
<strong>3)[readonly] 読込専用を切り替え</strong>
  <input type="text" [readonly]="checkValue" value="最上部チェックで読込専用"/><br />
<strong>4)[selected] 選択、未選択を切り替え</strong>
  <select>
    <option selected>選択肢1</option>
    <option>選択肢2</option>
    <option [selected]="checkValue">最上部チェックで有効</option>
  </select>
  `
})
export class AppComponent {
}

@NgModule({
  imports: [
    BrowserModule,
    FormsModule
  ],
  declarations: [
    AppComponent
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

platformBrowserDynamic().bootstrapModule(AppModule);

関連記事の目次

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください