【问题标题】:Get selected option text onChange获取选定的选项文本 onChange
【发布时间】:2016-10-30 19:05:18
【问题描述】:

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?

模板:

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

谢谢!

【问题讨论】:

    标签: angular


    【解决方案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>
    

    【讨论】:

      【解决方案2】:

      在 Angular 6 上这对我有用:

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

      【讨论】:

        【解决方案3】:

        您应该将一个对象传递给 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

        【讨论】:

          猜你喜欢
          • 2016-04-26
          • 1970-01-01
          • 1970-01-01
          • 2013-02-05
          • 1970-01-01
          • 2018-04-23
          相关资源
          最近更新 更多