我正在使用optgroup
个元素,我希望从一个组中选择option
元素以做出不同的反应并传递不同的数据。
但我设置的处理程序方法不会在这里触发。我错过了什么,或者是否在不支持的选项元素上设置点击事件?
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);
}
}
答案 0 :(得分:2)
option
元素不会触发点击事件。这不是Angular2的限制,而是浏览器限制。
您可以改为收听change
元素的select
事件,并从那里找出点击的option
元素。
答案 1 :(得分:1)
这个非angular2示例适用于Firefox 43.0.2,但不适用于Chrome 47.也许您会看到类似的行为?
<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/
(注意:快速示例,而非生产质量代码)