Angular中如何配置mat-select,使选中后仅显示shiftCode并附带对应颜色块
Angular中如何配置mat-select,使选中后仅显示shiftCode并附带对应颜色块
我来帮你搞定这个需求!要实现选中后只显示shiftCode加对应颜色块的效果,我们需要用到Angular Material的自定义选择触发器(mat-select-trigger),同时调整一下选项的绑定逻辑,这样才能拿到colorAssigned的值。下面是具体的修改步骤和完整代码:
核心改动点说明
- 把
mat-option的[value]从option.shiftCode改成整个option对象,这样选中后我们能获取到该选项的所有属性(包括colorAssigned) - 添加
mat-select-trigger标签,自定义选中后的显示内容:一个颜色块 +shiftCode文本 - 调整相关绑定逻辑,确保数据能正确传递
修改后的完整代码
<ng-container> <span class="font-weight-bold" [style.color]="this.calendarGrid[j][p].disable ? '#cbcccb' : null"> {{ this.calendarGrid[j][p].date }} </span> <mat-select [(value)]="this.calendarGrid[j][p].dropdownValue" (openedChange)="onDropdownToggle($event)" [pTooltip]="tooltipContent" tooltipPosition="bottom" [panelClass]="'custom-select-panel'" class="mat-select-custom-width-dropdown" (selectionChange)="onGridSelectionChange($event, j, p)" [disabled]="this.calendarGrid[j][p].disable" [ngClass]="this.calendarGrid[j][p].disable ? 'search_select-week' : ''" class="search_select_shift custom_placeholder w-100" placeholder="Select"> <!-- 自定义选中后的显示内容 --> <mat-select-trigger *ngIf="this.calendarGrid[j][p].dropdownValue"> <span class="color-block" [style.backgroundColor]="this.calendarGrid[j][p].dropdownValue.colorAssigned"> </span> {{ this.calendarGrid[j][p].dropdownValue.shiftCode }} </mat-select-trigger> <div class="mat_search"> <div class="search-icon"> <input type="text" name="filter-options" class="input_search" placeholder="Type..."> <img src="assets/img/search-icon.svg" alt="search-icon"> </div> <mat-option [value]="">Select</mat-option> <mat-option [value]="'A'">Weekly Off</mat-option> <!-- 这里把value改成整个option对象 --> <mat-option *ngFor="let option of shiftDropDownList" [value]="option" class="d-flex align-items-center"> {{ option.shiftCode + ' | ' + option.shiftStartTime + '-' + option.shiftEndTime }} <!-- 可以在这里也加上颜色块,让下拉选项更直观 --> <span class="color-block ml-auto" [style.backgroundColor]="option.colorAssigned"> </span> </mat-option> </div> </mat-select> </ng-container>
补充样式(可选)
给颜色块加一点基础样式,让它看起来更美观,在你的CSS文件里添加:
.color-block { display: inline-block; width: 16px; height: 16px; border-radius: 4px; margin-right: 8px; } /* 如果下拉选项里的颜色块要靠右,加上这个 */ .mat-option .color-block.ml-auto { margin-right: 0; margin-left: auto; }
注意事项
- 因为现在
dropdownValue绑定的是整个option对象,所以你需要在onGridSelectionChange方法里调整逻辑,比如原来拿$event.value是shiftCode字符串,现在变成了option对象,需要用$event.value.shiftCode来获取编码 - 如果“Weekly Off”这个选项也需要颜色块,可以给它也添加对应的colorAssigned值,或者单独处理显示逻辑
备注:内容来源于stack exchange,提问作者rishabh tripathi




