【问题标题】:How to get the selected value of a select option?如何获取选择选项的选定值?
【发布时间】:2019-10-15 22:18:53
【问题描述】:

我想在 Angular 7 中获取选择选项的选定值。使用 ngModel 进行双向数据绑定,我还在 app.module.ts 中导入了 FormsModule。

我的 HTML 文件:

<select (change)="selectChangeHandler($event)" 
[(ngModel)]="optSelected"> 
 <option *ngFor="let opt of options" [value]="opt.id"> 
{{opt.title}} 
</option> 
</select>

我的 TS 文件:

optSelected = 'aaa';
selectChangeHandler(event: any) {
  this.optSelected = event.target.value;
  console.log('The selected option is: ' + this.optSelected);
}

【问题讨论】:

标签: angular


【解决方案1】:

由于您使用ngModel/双向数据绑定,而不是使用change 事件,您可以简单地使用ngModelChange 事件绑定。根据documentation,是

在视图之后产生 ngModelChange 事件的事件发射器 模型更新。

<select (ngModelChange)="selectChangeHandler($event)" [(ngModel)]="optSelected"> 
  <option *ngFor="let opt of options" [value]="opt.id"> 
    {{opt.title}} 
  </option> 
</select>

在你的 component.ts 上,

selectChangeHandler() {
  console.log(this.optSelected);
}

【讨论】:

  • 嗨!仔细检查它,它工作得很好!谢谢!
猜你喜欢
  • 2020-05-26
  • 2015-05-09
  • 1970-01-01
  • 2019-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-26
  • 1970-01-01
相关资源
最近更新 更多