開発覚書はてな版

個人的な開発関連の備忘録

【Angular】optionタグで文字以外をvalueに設定する

概要

Angular の <option> への値設定で通常は value を使用します。
value に値を設定した場合は、変更後の値が文字列で設定されます。
ngValue に値を設定することで、文字列以外の値を扱えるようになります。

angular.io

実行環境

  • Node.js - 10.9.x

使用ライブラリ

  • Angular - 7.2.x

サンプルソース

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

interface TestData {
  id: number;
  name: string;
}

@Component({
  selector: 'app-root',
  template: `
    <div>
      <select [(ngModel)]="value" (change)="log()">
        <option [ngValue]="null">Not Selected</option>
        <ng-container *ngFor="let item of items">
          <option [ngValue]="item.id">{{item.name}}</option>
        </ng-container>
      </select>
      <button (click)="init()">Init</button>
      <button (click)="clear()">Clear</button>
    </div>
  `
})
export class AppComponent {

  items: TestData[] = [
    { id: 1, name: 'hige' },
    { id: 2, name: 'hoge' },
    { id: 3, name: 'hage' }
  ]

  value?: number = 2;

  clear(): void {
    this.value = null;
    this.log();
  }

  init(): void {
    this.value = 2;
    this.log();
  }

  log(): void {
    console.log('value:', this.value);
  }
}