如何实现Mat-Selection-List选项的级联启用/禁用?
实现mat-selection-list的级联启用/禁用逻辑
步骤1:修正数据类型错误
现有代码中disabled字段使用了字符串'true'/'false',但Angular的[disabled]绑定需要布尔值(true/false),非空字符串会被解析为true,导致错误的禁用状态。修改列表填充逻辑:
let arr = []; if (this.data.criteria.FirstSelection) { arr.push({ name: 'First Selection', selected: false, disabled: false, // 改为布尔值 }); } if (this.data.criteria.SecondSelection) { arr.push({ name: 'Second Selection', selected: false, disabled: true, // 改为布尔值 }); } if (this.data.criteria.ThirdSelection) { arr.push({ name: 'Third Selection', selected: false, disabled: true, // 改为布尔值 }); } if (this.data.criteria.FourthSelection) { arr.push({ name: 'Fourth Selection', selected: false, disabled: true, // 改为布尔值 }); } if (this.data.criteria.FifthSelection) { arr.push({ name: 'Fifth Selection', selected: false, disabled: true, // 改为布尔值 }); } if (this.data.criteria.SixthSelection) { arr.push({ name: 'Sixth Selection', selected: false, disabled: true, // 改为布尔值 }); } this.incomingParameters = arr;
步骤2:实现级联逻辑的点击事件处理
在组件的.ts文件中,完善GetChange方法,处理选中/取消选中后的级联启用/禁用:
GetChange(item: any) { const currentIndex = this.incomingParameters.indexOf(item); if (currentIndex === -1) return; // 通过ngModel绑定的selectedCriteria数组判断当前项是否被选中 const isSelected = this.selectedCriteria.includes(item.name); if (isSelected) { // 选中当前项:启用下一个选项(如果存在) if (currentIndex + 1 < this.incomingParameters.length) { this.incomingParameters[currentIndex + 1].disabled = false; } } else { // 取消选中当前项:禁用后面所有选项,并清除它们的选中状态 for (let i = currentIndex + 1; i < this.incomingParameters.length; i++) { const targetItem = this.incomingParameters[i]; targetItem.disabled = true; targetItem.selected = false; // 从selectedCriteria中移除已取消的选项 const criteriaIndex = this.selectedCriteria.indexOf(targetItem.name); if (criteriaIndex !== -1) { this.selectedCriteria.splice(criteriaIndex, 1); } } } }
步骤3:优化HTML绑定(避免冲突)
移除[selected]="item.selected"绑定,让[(ngModel)]="selectedCriteria"统一管理选中状态,避免双向绑定冲突:
<mat-selection-list id='selectedParameters' [(ngModel)]="selectedCriteria"> <mat-list-option *ngFor="let item of incomingParameters" [value]="item.name" [disabled]="item.disabled" checkboxPosition="before" (click)="GetChange(item)"> {{item.name}} </mat-list-option> </mat-selection-list>
步骤4:初始化时同步状态(可选)
如果存在默认选中的选项,初始化时需要自动启用后续选项,在填充完incomingParameters后添加以下逻辑:
// 初始化时根据已选中项设置后续选项的禁用状态 for (let i = 0; i < this.incomingParameters.length; i++) { const currentItem = this.incomingParameters[i]; if (currentItem.selected) { // 启用下一项 if (i + 1 < this.incomingParameters.length) { this.incomingParameters[i + 1].disabled = false; } } else { // 当前项未选中,后面所有项禁用 for (let j = i + 1; j < this.incomingParameters.length; j++) { this.incomingParameters[j].disabled = true; } break; // 前面项未选中,后续无需继续检查 } } // 同步selectedCriteria数组 this.selectedCriteria = this.incomingParameters .filter(item => item.selected) .map(item => item.name);
内容的提问来源于stack exchange,提问作者FlyFish
相关产品推荐
相关产品推荐

