Angular 12中Chrome浏览器select的option绑定(click)事件失效问题
问题原因
Chrome、Safari等webkit内核浏览器出于原生控件交互逻辑的设计限制,不会触发<option>标签上绑定的click、mousedown等鼠标事件,只有Firefox做了这部分的兼容实现,所以才会出现跨浏览器表现不一致的问题。
可行解决方案
你要的索引参数完全可以通过给<select>绑定change事件的方式拿到,不需要绑定option的click事件,有两种常用实现方案:
- 方案1:通过自定义属性存储索引
把迭代索引j存在option的自定义属性上,change事件触发后读取选中项的自定义属性即可:
模板代码:
对应TS逻辑:<select class="text-sm" (change)="onSelectChange(i, $event)"> <option value="" selected disabled>--</option> <option *ngFor="let option of item.opciones; let j = index" value="{{ option.id }}" [attr.data-index]="j"> {{ option.descripcion }} </option> </select>onSelectChange(i: number, event: Event) { const selectDom = event.target as HTMLSelectElement; const selectedOpt = selectDom.options[selectDom.selectedIndex]; const j = Number(selectedOpt.dataset.index); // 执行原有逻辑 this.updateItemsList(i, event, j); } - 方案2:通过ngValue直接传递包含索引的对象
如果使用Angular的表单能力,可以直接把索引和选项值封装成对象存在ngValue里,无需手动解析属性:
模板代码:
只需在组件中声明<select class="text-sm" [(ngModel)]="currentSelected" (change)="updateItemsList(i, $event, currentSelected.j)"> <option value="" selected disabled>--</option> <option *ngFor="let option of item.opciones; let j = index" [ngValue]="{id: option.id, j: j}"> {{ option.descripcion }} </option> </select>currentSelected变量即可使用,逻辑更简洁。
内容的提问来源于stack exchange,提问作者Oscar Morales
相关产品推荐
相关产品推荐

