获取选定的选项文本onChange

时间:2016-10-30 19:05:18

标签: angular

我知道当选择更改时如何获取所选选项(如下所示),但如何获取所选选项的 显示?< / 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);
}

谢谢!

3 个答案:

答案 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);
}
}

Plunker

答案 2 :(得分:2)

在Angular 6上,这对我有用:

let text = event.target.options[event.target.options.selectedIndex].text;