获取选定的选项文本onChange

goo*_*777 6 angular

我知道如何在选择更改时获取所选选项(如下所示),但如何获取所选选项的显示文本

模板:

<select (change)="onChange($event.target.value)">
    <option *ngFor="let option of activeDropdown.options" value="{{option.value}}">
        {{option.text}}
    </option>
</select>
Run Code Online (Sandbox Code Playgroud)

零件:

onChange(value: string) {
    console.log(value);
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Mah*_*kos 12

getSelectedOptionText(event: Event) {
   let selectElementText = event.target['options']
      [event.target['options'].selectedIndex].text;
      console.log(selectElementText);                                 
}
Run Code Online (Sandbox Code Playgroud)

HTML

<select name="" ngModel (change)="getSelectedOptionText($event)">
  <option *ngFor="let item of items" [value]="item.id">{{item.name}}
  </option>
</select>
Run Code Online (Sandbox Code Playgroud)


Baz*_*nga 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);
}
}
Run Code Online (Sandbox Code Playgroud)

Plunker


小智 6

在 Angular 6 上,这对我有用:

let text = event.target.options[event.target.options.selectedIndex].text;
Run Code Online (Sandbox Code Playgroud)