You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Material:根据其他下拉选择禁用单个下拉选项

问题根源与解决方案

核心问题

你写的disableOption函数完全无效,因为误解了响应式表单的结构:

  • psv是单个FormControl(仅存储下拉框的选中值),并非包含多个子控件的FormGroup。psvControl.get(optionValue)必然返回null,所以后续的disable()根本不会执行。
  • Angular Material的mat-option禁用逻辑,是通过给选项绑定[disabled]属性实现的,和表单控件的子元素操作无关。

正确实现方案

1. 组件类(form.component.ts):监听下拉框变化,维护禁用状态

import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { Subscription } from 'rxjs';

@Component({
  // 保留你的组件元数据
})
export class FormComponent implements OnInit, OnDestroy {
  reactiveForm: FormGroup;
  // 存储需要禁用的psv选项值
  disabledPsvOptions = new Set<string>();
  private lineOfBusinessSub?: Subscription;

  ngOnInit(): void {
    // 监听lineOfBusiness的选中值变化
    this.lineOfBusinessSub = this.reactiveForm.get('lineOfBusiness')?.valueChanges.subscribe(selectedValue => {
      this.disabledPsvOptions.clear();
      // 根据选中值设置需要禁用的选项
      if (selectedValue === 'commercial') {
        this.disabledPsvOptions.add('radar');
      }
      // 可扩展其他逻辑,比如选中residential时禁用特定选项
      // else if (selectedValue === 'residential') {
      //   this.disabledPsvOptions.add('heil');
      // }
    });
  }

  ngOnDestroy(): void {
    // 取消订阅,避免内存泄漏
    this.lineOfBusinessSub?.unsubscribe();
  }
}

2. 模板(form.component.html):给目标选项绑定禁用状态

修改psv下拉框的mat-option,给需要控制的选项添加[disabled]绑定:

<mat-form-field>
    <mat-label>Choose an option</mat-label>
    <mat-select id="lineOfBusiness" formControlName="lineOfBusiness">
        <mat-option value="commercial">Commercial</mat-option>
        <mat-option value="residential">Residential</mat-option>
        <mat-option value="industrial">Industrial</mat-option>
    </mat-select>
</mat-form-field>

<mat-form-field>
    <mat-label>Choose an option</mat-label>
    <mat-select id="psv" formControlName="psv">
        <mat-option value="inclinometer">Inclinometer</mat-option>
        <mat-option value="heil">Heil</mat-option>
        <mat-option value="radar" [disabled]="disabledPsvOptions.has('radar')">Radar</mat-option>
        <mat-option value="hydraulics">Hydraulics</mat-option>
        <mat-option value="coretex">Coretex</mat-option>
    </mat-select>
</mat-form-field>

简化版可选方案(无需TS状态变量)

如果逻辑简单,也可以直接在模板中通过表单控件值判断,省去TS中的状态维护:

<mat-option value="radar" [disabled]="reactiveForm.get('lineOfBusiness').value === 'commercial'">Radar</mat-option>

内容的提问来源于stack exchange,提问作者newby73

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 18:54:54