typescript 获取选定的值下拉 Angular 2

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40948478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:03:28  来源:igfitidea点击:

Getting selected value dropdown Angular 2

angulartypescript

提问by Arianule

struggling a bit to get selected value from drop down.

从下拉列表中获得选定的值有点挣扎。

As it is at the moment a value of undefinedis returned.

就像现在一样,undefined返回了 的值。

How can i get this selected value(opl.Opl_Id) in Angular 2?

我怎样才能在 Angular 2 中获得这个选定的值(opl.Opl_Id)?

<form class="form-inline" novalidate>
    <select class="form-control" (change)="onChange(opl)">
          <option [selected] = "opl.OplDescription == selectedOpl"  *ngFor="let opl of existingOpls" [ngValue]="opl.Opl_Id">{{opl.OplDescription}}</option>
    </select

//component
 onChange(value) {
    console.log(value);
}

回答by micronyks

Why do you call extra change event to just get the selected value??? Use [(ngModel)]to get updated value instead as shown below,

为什么要调用额外的更改事件来获取选定的值???使用[(ngModel)]如下图所示得到,而不是更新的值,

<select class="form-control" [(ngModel)]="selectedVal">              //<<<---here

      <option [attr.selected] = "opl.OplDescription == selectedOpl" //<<<---here
              *ngFor="let opl of existingOpls" 
              [ngValue]="opl.Opl_Id">
              {{opl.OplDescription}}
      </option>

</select>

{{selectedVal}}

回答by Dheeraj Kumar

I found this easier.. Hope it helps future developers.

我发现这更容易.. 希望它可以帮助未来的开发人员。

 <select class="form-control" id="select" (change)="Selected($event.target.value)">
        <option *ngFor="let item of items" [value]="item.id">{{item.value}}</option>
    </select>


    Selected(value: any) {

            console.log(value);

               }