1

I have a list-group got from ngFor as below. By clicking on any of a listed items, I can fire a click event and made the selection happening as I expected.

<div>
    <ul class="list-group my-3">
        <li class="list-group-item" 
        *ngFor="let category of categories"
        [class.active]="category.id === this.shopParams.categoryId"
        [value]="category.id"
        (click)="onCategorySelected(category.id)"
        >
        {{category.name}}
        </li>                
    </ul>
</div>

However, once I changed the list-group into a dropdown list, the click event seems never fired although an item can be selected by clicking it from the dropdown list.

<div>                    
      <select name="cars" class="custom-select mb-3">
          <option *ngFor="let category of categories" 
              [class.active]="category.id === this.shopParams.categoryId"
              [value]="category.id"
              (click)="onCategorySelected(category.id)"
              >
              {{category.name}}                       
          </option>                    
      </select>
 </div>

Here is my click function in component.ts

onCategorySelected(categoryId: number) {
    const params = this.shopService.getShopParams();
    params.categoryId = categoryId;
    this.shopService.setShopParams(params);
}

Can any one point out what the problem is and help me out with correction?

canbrian
  • 109
  • 1
  • 3
  • 13

1 Answers1

0

Here is how you can do to get the selected value:

<div>
    <select name="cars" class="custom-select mb-3" (change)="onCategorySelected($event.target.value)">
          <option *ngFor="let category of categories" 
              [value]="category.id"
              >
              {{category.name}}                       
          </option>                    
      </select>
</div>

Note the change event on the select. I pass the $event.target.value in the onCategorySelected() method to get the selected id.

For some reason, the click event does not works directly on the option tag, at least with the default select tag from html.

Also here is a link if you need more possible solution to get values from a select.

Quentin Grisel
  • 4,794
  • 1
  • 10
  • 15