我创建了一个包含选项的选择列表,当选择一个选项时,我希望能够读取选择的选项是什么。
当我尝试阅读该选项时,它会返回可供选择的每个选项的完整列表。
这些选项是从数组创建的,并使用 *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)
}
}
在此处查看示例
目前,这返回Enter/Select FruitApplePearBananaOrange
,例如我只想Orange
。
如何仅返回所选选项?另外,我不想有一个提交按钮,我希望该功能在选项更改时运行,因此使用 (change)
.
设置[(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)
}