Angular:如何从HTMLSelectElement获取绑定的Category对象?
问题原因
原生HTML <select> 的 value 属性仅支持字符串类型,当你通过模板引用变量 categorySelect.value 获取值时,绑定的 Category 对象会被强制转为字符串,结果就是 [object Object]。
可行解决方案
不需要替换原生select组件,通过以下两种方式就能直接拿到原对象:
方案1:使用Angular双向绑定(推荐)
这是最符合Angular开发习惯的方式,利用 [(ngModel)] 自动绑定选中的对象:
模板代码
<select [(ngModel)]="selectedCategory" (ngModelChange)="goToCategory.emit(selectedCategory)" style="..."> <option selected hidden>All</option> <option [ngValue]="category" *ngFor="let category of categories"> {{category.groupName}} </option> </select>
组件代码
selectedCategory: Category | null = null; @Output() goToCategory = new EventEmitter<Category>();
选中项变化时,selectedCategory 会自动同步为对应的 Category 对象,直接emit即可。
方案2:直接获取option的ngValue属性
如果不想引入双向绑定,可通过模板引用变量直接获取选中option的ngValue(Angular为绑定[ngValue]的option附加的专属属性,专门存储非字符串值):
模板代码
<select #categorySelect (change)="goToCategory.emit(categorySelect.selectedOptions[0].ngValue)" style="..."> <option selected hidden>All</option> <option [ngValue]="category" *ngFor="let category of categories"> {{category.groupName}} </option> </select>
这里通过 categorySelect.selectedOptions[0] 拿到选中的option元素,再取其ngValue属性即可得到原Category对象。
内容的提问来源于stack exchange,提问作者user12696219
相关产品推荐
相关产品推荐

