如何根据选中项禁用mat-select选项?含双选择框场景需求
实现mat-select的双向禁用逻辑
步骤1:组件类定义变量与方法
在组件类中声明选项数组、选中值变量,以及判断选项是否禁用的核心方法:
import { Component } from '@angular/core'; import { MatSelectChange } from '@angular/material/select'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { options = ['all', 'Option 1', 'Option 2', 'Option 3']; selectedValue1: string; selectedValue2: string; isOptionDisabled(option: string, currentSelect: 'select1' | 'select2'): boolean { const otherSelectValue = currentSelect === 'select1' ? this.selectedValue2 : this.selectedValue1; // 需求1:当前选择器选中'all'时,禁用当前选择器的其他选项 if ((currentSelect === 'select1' && this.selectedValue1 === 'all') || (currentSelect === 'select2' && this.selectedValue2 === 'all')) { return option !== 'all'; } // 需求1:另一个选择器选中'all'时,禁用当前选择器的所有选项 if (otherSelectValue === 'all') { return true; } // 需求2:当前选项已在另一个选择器中被选中,禁用该选项 return option === otherSelectValue; } // 可选:选中'all'时清空另一个选择器的选中值,避免状态冲突 onSelectChange(event: MatSelectChange, selectId: 'select1' | 'select2') { if (event.value === 'all') { this.selectedValue1 = selectId === 'select1' ? 'all' : undefined; this.selectedValue2 = selectId === 'select2' ? 'all' : undefined; } } }
步骤2:模板中绑定禁用逻辑
在模板的mat-option上通过[disabled]绑定上述方法,同时添加选中事件处理:
<mat-form-field appearance="fill" style="margin-right: 20px;"> <mat-label>选择器1</mat-label> <mat-select [(value)]="selectedValue1" (selectionChange)="onSelectChange($event, 'select1')"> <mat-option *ngFor="let opt of options" [value]="opt" [disabled]="isOptionDisabled(opt, 'select1')" > {{ opt }} </mat-option> </mat-select> </mat-form-field> <mat-form-field appearance="fill"> <mat-label>选择器2</mat-label> <mat-select [(value)]="selectedValue2" (selectionChange)="onSelectChange($event, 'select2')"> <mat-option *ngFor="let opt of options" [value]="opt" [disabled]="isOptionDisabled(opt, 'select2')" > {{ opt }} </mat-option> </mat-select> </mat-form-field>
逻辑说明
- 选中'all'时的禁用规则:
- 若当前选择器选中
all,则该选择器内的其他选项全部禁用,仅保留all可选; - 若另一个选择器选中
all,则当前选择器的所有选项直接禁用。
- 若当前选择器选中
- 跨选择器的选项禁用:
- 当某选择器选中非
all的选项时,该选项会在另一个选择器中被禁用,避免重复选择。
- 当某选择器选中非
- 可选的状态重置:
- 通过
onSelectChange方法,在选中all时清空另一个选择器的选中值,避免出现选中值与禁用状态冲突的情况。
- 通过
内容的提问来源于stack exchange,提问作者user18067747
相关产品推荐
相关产品推荐

