Angular 2选项(下拉列表) - 如何在变化时获取值,以便可以在函数中使用? [英] Angular 2 select option (dropdown) - how to get the value on change so it can be used in a function?

查看:114
本文介绍了Angular 2选项(下拉列表) - 如何在变化时获取值,以便可以在函数中使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用一些值构建下拉列表。

I am trying to build a drop down with a few values.

但是,在选择值时,我想进行一个带有id的API调用。

However, on selecting a value, I want to make an API call that takes an id.

在我的component.ts中,我有一系列值:

In my component.ts, I have an array of values:

values = [
  { id: 3432, name: "Recent" },
  { id: 3442, name: "Most Popular" },
  { id: 3352, name: "Rating" }
];

在我的模板中,我使用的数组如下:

In my template, I am using that array as follows:

<select>
  <option *ngFor="let v of values" [value]="v">  
    {{v.name}}
  </option>
</select>

但是,从下拉列表中选择一个值时,如何访问 id 属性?我想在我的函数中使用它 getPhotosByType(id)

However, on picking a value from the drop down, how can I access the id property? I want to use that in my function getPhotosByType(id).

谢谢

推荐答案

我的答案有点迟,但很简单;但未来可能会帮助别人;
我使用 $ event (目前最新)对4.4.3,5.1 +,6.x和7.x进行了角度测试

My answer is little late but simple; but may help someone in future; I did experiment with angular both 4.4.3, 5.1+, 6.x and 7.x using $event (latest at the moment)

模板:

<select (change)="onChange($event)">
    <option *ngFor="let v of values" [value]="v.id">{{v.name}}</option>
</select>

TS

export class MyComponent {
  public onChange(event): void {  // event will give you full breif of action
    const newVal = event.target.value;
    console.log(newVal);
  }
}

这篇关于Angular 2选项(下拉列表) - 如何在变化时获取值,以便可以在函数中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆