Reputation: 1476
I've created a select list with options, and when an option is selected I want to be able to read what the option that was selected was.
When I try read the option it returns the full list of every option that was available to choose.
The options are created from an array and displayed using *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)
}
}
View example here
Currently, this returns Enter/Select FruitApplePearBananaOrange
, I want just Orange
for example.
How do I return just the selected option?
Also, I do not want to have a submit button, I want the function to run when the option changes hence the use of (change)
.
Upvotes: 1
Views: 43
Reputation: 22203
You have to set [(ngModel)]="selectedFruit" (change)="fruity($event)"
or (change)="fruity($event.target.value)"
Try this:
<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)
}
Upvotes: 1