1

I'm working with optgroup elements where I want selection of option elements from one group to react differently and pass along different data than others.

But the handler methods I've set aren't firing here. Am I missing something, or is setting click events on option elements not supported?

import {Component} from 'angular2/core';
import {NgFor} from 'angular2/common';
import {City, County, RegionalData} from './interfaces';
import {api} from './api.service';

@Component({
    selector: 'geo-selector',
    template: `
        <div>
            <select name="region-selector">
                <option disabled="disabled" selected="selected">Select a city/county</option>
                <optgroup label="Cities">
                    <option *ngFor="#city of cities" [value]="city" (click)="onCitySelect(city)">{{city.name}}</option>
                </optgroup>
                <optgroup label="Counties">
                    <option *ngFor="#county of counties" [value]="county" (click)="onCountySelect(county)">{{county.name}}</option>
                </optgroup>
            </select>
            <label for="">Zip Search</label>
            <input type="text" name="zip-search"/>
        </div>
                        `,
    providers: [api],
    directives: [NgFor]
})

export class GeoSelector {
        public cities: City[];
        public counties: County[];
        public selectedRegion: any;

        constructor(private _api:api) {
            this.getRegions();
        }

        getRegions(): void {
            this._api.getRegions().then((data: RegionalData) => {
                let cities = this.cities = data.cities;
                let counties = this.counties = data.counties;
                this.selectedRegion = cities[0] ? cities[0] : counties[0];
            });
        }

        onCitySelect(region) : void {
            console.log(region);
        }


        onCountySelect(region): void {
            console.log(region);
        }

}
Bryce Johnson
  • 6,689
  • 6
  • 40
  • 51
  • You could use `change` see here http://stackoverflow.com/questions/33700266/how-can-i-get-new-selection-in-select-in-angular-2 – Ashley Coolman Dec 24 '15 at 14:25

2 Answers2

2

The option element doesn't fire click events. This is not a limitation of Angular2 but a browser limitation. You can listen to the change event of the select element instead and the from there figure out what option element was clicked.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
1

This non-angular2 example works in Firefox 43.0.2, but not in Chrome 47. Perhaps you're seeing a similar behavior?

<select>
  <option></option>
  <option onclick="alert('option test');">Test Option</option> <!-- does not work -->
</select>

<button onclick="alert('button test');">Test Button</button> <!-- works -->

https://jsfiddle.net/t7xzxrtw/2/

(Note: Quick example, not production quality code)

kendaleiv
  • 5,793
  • 3
  • 28
  • 38