LoginSignup
0
2

More than 1 year has passed since last update.

Angularのセレクトボックス に初期値を入れる時につまづいた話

Posted at

1. 背景

Angularを使ったアプリの拡張開発を行っていた時に、プルダウン形式のセレクトボックスに初期値を入れようとしたところ、なかなかうまくいかず悩みました。
参考のサイトも調べつつ、今回のやり方でうまく行きました。

2. 結論

結論から言うと、最初のform-controlの箇所で、ngModelにプルダウンのvalueとは別の変数を入れてあげることで解消しました。

#sample.component.html
<select id="sample" [(ngModel)]="defaultValue">
  <option [value]="undefined">初期値</option> → ここのテキスト文が初期値として表示される
  <option *ngFor="let sampleValue of sampleValues" [value]="sampleValue">
    {{sampleValue}}
  </option>
</select>

#sample.component.ts
public defaultValue = undefined; → ここの変数とngModelで指定する変数を合わせる
public sampleValues: string[] =[
    'value1', 'value2', 'value3'
];
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2