我知道当选择更改时如何获取所选选项值(如下所示),但如何获取所选选项的 显示?< / p>
模板:
<select (change)="onChange($event.target.value)">
<option *ngFor="let option of activeDropdown.options" value="{{option.value}}">
{{option.text}}
</option>
</select>
组件:
onChange(value: string) {
console.log(value);
}
谢谢!
答案 0 :(得分:12)
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>
答案 1 :(得分:6)
您应该将对象传递给ngValue并使用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);
}
}
答案 2 :(得分:2)
在Angular 6上,这对我有用:
let text = event.target.options[event.target.options.selectedIndex].text;