Select-Option returns 每个选项不只是选择的选项
Select-Option returns every option not just selected option
我创建了一个包含选项的 select 列表,当一个选项被 selected 时,我希望能够读取 selected 的选项是什么。
当我尝试阅读该选项时,它 return 是可供选择的每个选项的完整列表。
选项是从数组创建的,并使用 *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
目前,这个 returns Enter/Select FruitApplePearBananaOrange
,例如我只想要 Orange
。
如何 return 仅 selected 选项?
Also, I do not want to have a submit button, I want the function to 运行 when the option changes hence the use of (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)
}
我创建了一个包含选项的 select 列表,当一个选项被 selected 时,我希望能够读取 selected 的选项是什么。
当我尝试阅读该选项时,它 return 是可供选择的每个选项的完整列表。
选项是从数组创建的,并使用 *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
目前,这个 returns Enter/Select FruitApplePearBananaOrange
,例如我只想要 Orange
。
如何 return 仅 selected 选项?
Also, I do not want to have a submit button, I want the function to 运行 when the option changes hence the use of (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)
}