如何禁用Angular MatSelect多选模式下的自动排序功能?
禁用MatSelect多选模式下的自动排序,保留选择顺序
MatSelect多选模式默认会按选项列表的顺序自动排序选中结果,要实现按选择顺序保存和显示,需要手动维护选中数组的顺序,具体步骤如下:
1. 修改HTML模板
- 给每个
mat-option绑定点击事件,手动处理选中/取消选中逻辑 - 添加
mat-select-trigger自定义选中标签的显示,确保按选择顺序展示
<div class="input pt-2 w-full"> <mat-form-field class="w-full"> <mat-select formControlName="staffInvolved" multiple> <!-- 自定义选中标签的显示 --> <mat-select-trigger> {{ formGroup.get('staffInvolved')?.value.map(item => item.nameShow).join(', ') }} </mat-select-trigger> <!-- 绑定点击事件处理选中逻辑 --> <mat-option *ngFor="let participant of listManager" [value]="participant" (click)="toggleParticipantSelection(participant)"> {{ participant.nameShow }} </mat-option> </mat-select> </mat-form-field> </div>
2. 在TS中实现选中逻辑
通过点击事件手动维护选中数组,判断当前项是否已选中:
- 未选中则添加到数组末尾
- 已选中则从数组中移除对应项
formGroup = this.fb.group({ staffInvolved: [[], [Validators.required]], }); // 用参与者对象的唯一标识(如id/code)判断是否已选中 toggleParticipantSelection(participant: any) { const control = this.formGroup.get('staffInvolved'); if (!control) return; const currentSelection = control.value as any[]; const existingIndex = currentSelection.findIndex(item => item.id === participant.id); if (existingIndex > -1) { // 移除已选中的项 control.setValue([ ...currentSelection.slice(0, existingIndex), ...currentSelection.slice(existingIndex + 1) ]); } else { // 添加新选中的项到末尾,保持选择顺序 control.setValue([...currentSelection, participant]); } }
说明
- 替换
item.id为你业务中参与者对象的实际唯一标识字段(如code、userId等),确保判断准确 mat-select-trigger会按我们维护的数组顺序渲染选中标签,与选择顺序一致- 表单控件的值会同步为手动维护的数组,提交时也会保持选择顺序
内容的提问来源于stack exchange,提问作者Dương Huy HIếu
相关产品推荐
相关产品推荐

