How to make an event listener for <select><option> forms in Angular?

Viewed 20

I want a handler function in the controller to fire when the user clicks an option in a <select><option> in the HTML view. MDN Web Docs says to do it this way:

<label>Choose an ice cream flavor:
  <select class="ice-cream" name="ice-cream">
    <option value="">Select One …</option>
    <option value="chocolate">Chocolate</option>
    <option value="sardine">Sardine</option>
    <option value="vanilla">Vanilla</option>
  </select>
</label>

<div class="result"></div>
const selectElement = document.querySelector('.ice-cream');

selectElement.addEventListener('change', (event) => {
  const result = document.querySelector('.result');
  result.textContent = `You like ${event.target.value}`;
});

I copied and pasted the HTML ice cream picker into an Angular HTML view. Then in the controller I made:

export class AppComponent {
  selectElement: any;
  result: any;

  ngOnInit() {
    this.selectElement = document.querySelector('.ice-cream');

    this. selectElement.addEventListener('change', (event) => {
      this.result = document.querySelector('.result');
      console.log(${event.target.value});
    });
  }
}

That didn't work. Don't we already have event listeners in Angular? Can I do something like this:

<form (select)="onSelect()">
  <label>Choose an ice cream flavor:
    <select class="ice-cream" name="ice-cream">
      <option value="">Select One …</option>
      <option value="chocolate">Chocolate</option>
      <option value="sardine">Sardine</option>
      <option value="vanilla">Vanilla</option>
    </select>
  </label>
</form>

I want the form to know when the user selects an option, then fire the handler function and pass the selection.

1 Answers

Use change method in select tag

<select (change)="updateSorting($event)">
  <option disabled selected>Sorting</option>
  <option value="pointDes">pointDes</option>
  <option value="timeDes">timeDes</option>
  <option value="timeAsc">timeAsc</option>
  <option value="pointAsc">pointAsc</option>
</select>
Related