hoge.ts
// プロパティバインディング [ ]
// 動的な値をバインド
<mat-select [aria-label]="labelText">
// TypeScriptコンポーネント
labelText = '国選択';
// イベントバインディング ( )
// イベントのバインド
<mat-select (selectionChange)="onSelectionChange($event)">
// コンポーネント
onSelectionChange(event: MatSelectChange) {
console.log('選択された値:', event.value);
}
// 双方向バインディング [( )](バナナインザボックス構文)
// 値の読み書き両方
<mat-select [(value)]="selectedCountry">
// コンポーネント
selectedCountry = 'jp';
// テンプレート参照変数 #
// テンプレート内で要素を参照
<mat-select #countrySelect>
<button (click)="countrySelect.open()">開く</button>
// 文字列の属性バインド(バインドなし)
// 静的な文字列を直接設定
<mat-select aria-label="国選択">
// 実践的な使用例:
<mat-select
[aria-label]="'国選択'" // プロパティバインディング
[(ngModel)]="selectedCountry" // 双方向バインディング
(selectionChange)="onCountryChange($event)" // イベントバインディング
[disabled]="isDisabled" // 条件に基づくプロパティバインディング
>
<mat-option *ngFor="let country of countries" [value]="country.code">
{{country.name}}
</mat-option>
</mat-select>
// コンポーネント
export class CountrySelectComponent {
selectedCountry: string;
isDisabled = false;
countries = [
{ code: 'jp', name: '日本' },
{ code: 'us', name: 'アメリカ' }
];
onCountryChange(event: MatSelectChange) {
console.log('選択された国:', event.value);
}
}
バインディングの使い分け
[ ] :
動的な値を設定する場合
TypeScriptの値をHTMLに反映させたい場合
( ) :
ユーザーのアクションを検知したい場合
コンポーネントの変更を監視したい場合
[( )] :
フォーム入力など、双方向のデータの流れが必要な場合
ビューとモデルを同期させたい場合
バインドなし(直接記述):
静的な文字列を設定する場合
値が変更されない場合
注意点:
プロパティバインディングを使用する場合、式の評価結果が代入されます
イベントバインディングは$eventオブジェクトでイベントデータにアクセスできます
双方向バインディングは内部的にプロパティバインディングとイベントバインディングの組み合わせです