I know how to get the selected option value when a select changes (as shown below), but how do I get the displayed text of the selected option?
Template:
<select (change)="onChange($event.target.value)">
<option *ngFor="let option of activeDropdown.options" value="{{option.value}}">
{{option.text}}
</option>
</select>
Component:
onChange(value: string) {
console.log(value);
}
Thanks!
Or to get the text of the option, use text() : $var = jQuery("#dropdownid option:selected"). text(); alert ($var);
We can select text or we can also find the position of a text in a drop down list using option:selected attribute or by using val() method in jQuery. By using val() method : The val() method is an inbuilt method in jQuery which is used to return or set the value of attributes for the selected elements.
Use the selectedIndex Property We can get the index of the selected item with the selectedIndex property. Then we can use the text property to get the text of the selected item. We create the getSelectedText function that takes an element as the parameter. Then we check if selectedIndex is -1.
getSelectedOptionText(event: Event) {
let selectElementText = event.target['options']
[event.target['options'].selectedIndex].text;
console.log(selectElementText);
}
HTML
<select name="" ngModel (change)="getSelectedOptionText($event)">
<option *ngFor="let item of items" [value]="item.id">{{item.name}}
</option>
</select>
On Angular 6 this worked for me:
let text = event.target.options[event.target.options.selectedIndex].text;
You should pass an object to ngValue and use ngModel:
@Component({
selector: 'my-app',
template: `
<div>
<select [ngModel]="active" (ngModelChange)="onChange($event)">
<option *ngFor="let option of activeDropdown.options" [ngValue]="option">
{{option.text}}
</option>
</select>
</div>
`,
})
export class App {
activeDropdown;
constructor() {
this.active = {};
this.activeDropdown = {
options: [{text: 'One', value: 1}, {text: 'Two', value: 2}]
}
}
onChange(event: string) {
console.log(event.text);
}
}
Plunker
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With