Javascript Angular 2 选择选项(下拉菜单) - 如何获取更改时的值以便它可以在函数中使用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39501595/
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-08-23 22:38:20  来源:igfitidea点击:

Angular 2 select option (dropdown) - how to get the value on change so it can be used in a function?

javascripthtmlangulartypescript

提问by user1354934

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

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

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

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

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

在我的 component.ts 中,我有一个值数组:

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>

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

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

Thanks

谢谢

回答by mumair

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

我的回答有点晚,但很简单;但将来可能会帮助某人;我使用$event(目前最新)对4.4.3、5.1+、6.x、7.x 和 8.x 等角度版本进行了实验

Template:

模板:

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

TS

TS

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

回答by Paul Samsotha

You need to use an Angular form directive on the select. You can do that with ngModel. For example

您需要在select. 你可以用ngModel. 例如

@Component({
  selector: 'my-app',
  template: `
    <h2>Select demo</h2>
    <select [(ngModel)]="selectedCity" (ngModelChange)="onChange($event)" >
      <option *ngFor="let c of cities" [ngValue]="c"> {{c.name}} </option>
    </select>
  `
})
class App {
  cities = [{'name': 'SF'}, {'name': 'NYC'}, {'name': 'Buffalo'}];
  selectedCity = this.cities[1];

  onChange(city) {
    alert(city.name);
  }
}

The (ngModelChange)event listener emits events when the selected value changes. This is where you can hookup your callback.

(ngModelChange)事件侦听器发射事件所选择的值更改时。这是您可以连接回调的地方。

Note you will need to make sure you have imported the FormsModuleinto the application.

请注意,您需要确保已将 导入FormsModule到应用程序中。

Here is a Plunker

这是一个Plunker

回答by Rinold

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

private ValueId : number = 0 // this will be used for multi access like 
                             // update, deleting the obj with id.
private selectedObj : any;

private selectedValueObj(id: any) {
  this.ValueId = (id.srcElement || id.target).value;
  for (let i = 0; i < this.values_of_objArray.length; i++) {
    if (this.values_of_objArray[i].id == this.ValueId) {
      this.selectedObj = this.values_of_objArray[i];
    }
  }
}

Now play with this.selectedObjwhich has the selected obj from the view.

现在播放this.selectedObj从视图中选择的对象。

HTML:

HTML:

<select name="values_of_obj" class="form-control" [(ngModel)]="ValueId"  
        (change)="selectedValueObj($event)" required>

  <option *ngFor="let Value of values_of_objArray"
          [value]="Value.id">{{Value.name}}</option>    
</select>

回答by Nabin Kumar Khatiwada

Another solution would be,you can get the object itself as value if you are not mentioning it's id as value: Note: [value] and [ngValue] both works here.

另一个解决方案是,如果您没有将对象的 id 作为值提及您可以将对象本身作为值注意:[value] 和 [ngValue] 都在这里工作。

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

In ts:

在 ts:

your_method(v:any){
  //access values here as needed. 
  // v.id or v.name
}

Note: If you are using reactive form and you want to catch selected value on form Submit, you should use [ngValue]directive instead of [value]in above scanerio

注意:如果您使用的是响应式表单并且您想在表单提交中捕获选定的值,您应该使用[ngValue]指令而不是上面 scanerio 中的[value]

Example:

例子:

  <select (change)="your_method(values[$event.target.selectedIndex])" formControlName="form_control_name">
      <option *ngFor="let v of values" [ngValue]="v" >  
        {{v.name}}
      </option>
    </select>

In ts:

在 ts:

form_submit_method(){
        let v : any = this.form_group_name.value.form_control_name;  
    }

回答by VIKAS KOHLI

Template/HTML File (component.ts)

模板/HTML 文件 (component.ts)

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

Typescript File (component.ts)

打字稿文件(component.ts)

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

onChange(cityEvent){
    console.log(cityEvent); // It will display the select city data
}

(ngModelChange) is the @Output of the ngModel directive. It fires when the model changes. You cannot use this event without the ngModel directive

(ngModelChange) 是 ngModel 指令的@Output。当模型改变时它会触发。如果没有 ngModel 指令,您将无法使用此事件

回答by JFB

<select [(ngModel)]="selectedcarrera" (change)="mostrardatos()" class="form-control" name="carreras">
    <option *ngFor="let x of carreras" [ngValue]="x"> {{x.nombre}} </option>
</select>

In ts

在 ts

mostrardatos(){

}