Angular中MatSelectionListChange事件值为undefined问题
解决MatSelectionList变更事件中获取元素值为undefined的问题
我明白你遇到的困扰了——点击选择列表项时,明明checked状态是正确的,但就是拿不到对应元素的值,打印event时看到值是undefined对吧?这其实是因为你没给mat-list-option绑定value属性导致的。
问题根源
mat-selection-list的MatSelectionListChange事件里的option对象,它的value属性默认是undefined,除非你显式给mat-list-option指定[value]绑定,不然不管选中状态怎么变化,都拿不到对应的数据内容。
修复步骤
给mat-list-option添加value绑定
修改你的HTML代码,给每个mat-list-option绑定[value]到对应的label(或者你业务需要的其他关联值):<div> <mat-selection-list #costUnits [(ngModel)]="selectedCostUnits" (selectionChange)="onSelectionChange($event)" > <mat-list-option *ngFor="let label of labels" [value]="label" selected="true"> {{ label }} </mat-list-option> </mat-selection-list> </div>在事件处理中获取对应的值
现在你就可以在onSelectionChange里拿到正确的值了,比如:onSelectionChange(event: MatSelectionListChange) { // 获取当前变更的选项的值 const changedValue = event.option.value; // 获取当前选项的选中状态 const isSelected = event.option.selected; console.log('变更的值:', changedValue, '选中状态:', isSelected); // 如果需要获取所有选中的选项集合 const allSelectedValues = event.source.selectedOptions.selected.map(option => option.value); console.log('所有选中值:', allSelectedValues); }
这样修改后,不管你点击已选中的元素切换状态,都能正确拿到对应的元素值,而不是undefined了。
内容的提问来源于stack exchange,提问作者uhetz
相关产品推荐
相关产品推荐

