Select-Option返回每个选项,而不仅仅是选定的选项

时间:2019-05-31 12:48:06

标签: angular html-select

我已经创建了一个带有选项的选择列表,当选择一个选项时,我希望能够读取所选择的选项。
当我尝试阅读该选项时,它将返回可供选择的每个选项的完整列表。

选项是通过数组创建的,并使用*ngFor显示。

.component.html

<form action="">
    <select id ="fruitSelect" (change)="fruity()" name="fruitSelect" autofocus >
      <option>Enter/Select Fruit</option>
      <option  *ngFor="let fruit of fruits" value="fruit">{{fruit}}</option>
    </select>
  </form>

.component.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  fruits: any = ['Apple', 'Pear', 'Banana', 'Orange']

  fruity() {
    var e = document.getElementById("fruitSelect")
    console.log(e.textContent)
  }
}

查看示例here

当前,它返回Enter/Select FruitApplePearBananaOrange,例如,我只想要Orange

如何仅返回所选选项? 另外,我不想有一个提交按钮,我希望函数在选项更改时运行,从而使用(change)

1 个答案:

答案 0 :(得分:0)

您必须设置[(ngModel)]="selectedFruit" (change)="fruity($event)"(change)="fruity($event.target.value)"

尝试一下:

<select id ="fruitSelect" (change)="fruity($event)" name="fruitSelect" autofocus [(ngModel)]="selectedFruit">
  <option>Enter/Select Fruit</option>
  <option  *ngFor="let fruit of fruits" [value]="fruit">{{fruit}}</option>
</select>

TS:

 fruity(selectedValue) {      
    console.log(selectedValue)
  }
相关问题