typescript 将操作添加到 Select (Angular 4) 上的选项

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

Add action to option on Select (Angular 4)

angulartypescript

提问by Gustavo

I want Angular to execute the function "onEditClick" when the user click on an specif option, here's my code:

当用户单击特定选项时,我希望 Angular 执行“onEditClick”函数,这是我的代码:

<select class="form-control">
  <option *ngFor="let skill of skills" (click)="onEditClick(skill)" >{{ skill.name }}</option>
</select>

When I click on any option, nothing happens.

当我单击任何选项时,什么也没有发生。

I tried doing it with a table instead of select and it worked:

我尝试用表格而不是选择来做它并且它起作用了:

<tbody *ngFor="let skill of skills">
  <td> {{ skill.name }} </td>
<td><button class="btn btn-outline-success" height="20" width="20" (click)="onEditClick(skill)">Edit</button></td>
</tbody>

How do I do it with the Select one?

我如何使用 Select one 做到这一点?

回答by lingthe

Click event is not valid option for select, you should use change event

单击事件不是选择的有效选项,您应该使用更改事件

 <select class="form-control" (change)="onEditClick($event.target.value)">
   <option *ngFor="let skill of skills">
      {{ skill.name }}
   </option>
 </select>

then in your component do something with that

然后在你的组件中做一些事情

onEditClick(skill: any) { console.log('skill name', skill) }

onEditClick(skill: any) { console.log('skill name', skill) }

You can also pass some other parameter of skill object as a value like id, using [value]="skill.id"

您还可以将技能对象的一些其他参数作为 id 之类的值传递,使用 [value]="skill.id"

<option *ngFor="let skill of skills" [value]="skill.id">

<option *ngFor="let skill of skills" [value]="skill.id">

But if you want to get full skillobject maybe you can do this with [(ngModel)] and (change), like this:

但是如果你想获得完整的技能对象,也许你可以用 [(ngModel)] 和 (change) 来做到这一点,就像这样:

<select class="form-control" [(ngModel)]="selectedSkill" 
(change)="getSelectedSkill()">
 <option *ngFor="let skill of skills" [ngValue]="skill">
    {{ skill.name }}
 </option>
</select>

and than in your component :

而不是在您的组件中:

selectedSkill: any

selectedSkill: any

getSelectedSkill(){ console.log(this.selectedSkill) }

getSelectedSkill(){ console.log(this.selectedSkill) }