0

Currently I'm working on an Angular project.

I want to create a select button that calls a function in my .ts file when I click on one of the options. It has to send the chosen option with it.

Right now I'm using the following code:

In my HTML

<select class="btn add" (change)="onChange($event.target.value)">
    <option value="" disabled selected>Choose...</option>
    <option *ngFor="let option of listOfOptions >{{option}}</option>
</select>

In my .TS

private listOfOptions = ['delete'];

And the function that has to be triggered.

onChange(option) {
    if(option = 'delete') {
      console.log('Triggered delete!');
  }
}

As you can see currently I'm using the (change) event. But when it's on 'Delete' and you would click 'delete' again thats not working. So therefor I want to change it to something like (click). But when I do that it triggers on opening the selector instead of when chosing an option.

How do I make it so it always triggers when I'm choosing an option inside the selector, but not the selector itself?

Lars
  • 53
  • 1
  • 4
  • See a working example here: https://stackblitz.com/edit/angular-zmazjl?file=src%2Fapp%2Fapp.component.css – Ashish Ranjan May 22 '19 at 12:04
  • Possible duplicate of [Run change event for select even when same option is reselected](https://stackoverflow.com/questions/7742739/run-change-event-for-select-even-when-same-option-is-reselected) – Ashish Ranjan May 22 '19 at 12:07

2 Answers2

0

Put the change listener on the select tag instead.

<select (change)="onChange(...)">
Dzhavat Ushev
  • 725
  • 4
  • 13
  • Thats what I have already, but it doesnt work the way I want it to. – Lars May 22 '19 at 10:41
  • My answer was actually related to the initial version of your question. You've updated it since so I can see my answer wont solve your problem. :) – Dzhavat Ushev May 22 '19 at 10:43
0

You can do this:

<option (click)="yourFunction()">

You can put an argument so you can see the option clicked.

Orestis Zekai
  • 897
  • 1
  • 14
  • 29