你能在选项元素上设置点击事件吗?(Angular v2.0.0-beta.0)

Can you set click events on option elements? (Angular v2.0.0-beta.0)

本文关键字:Angular v2 0-beta 事件 选项 元素 设置      更新时间:2023-09-26

我使用的是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);
        }
}

option元素不会触发点击事件。这不是Angular2的限制,而是浏览器的限制。您可以改为监听select元素的change事件,然后从中找出单击了什么option元素。

这个非语言2示例适用于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/

(注意:快速示例,而非生产质量代码)