Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add action to option on Select (Angular 4)

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

<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?

like image 893
Gustavo Avatar asked Nov 28 '22 22:11

Gustavo


1 Answers

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) }

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

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

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

<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

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

like image 94
lingthe Avatar answered Dec 06 '22 13:12

lingthe