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

Angular+Material场景下如何根据checkbox勾选状态禁用指定输入框

实现方案

逻辑说明

你需要实现的逻辑仅针对「Other Contingencies」对应的输入框(其余复选框无关联输入框):仅当「Other Contingencies」复选框被选中时输入框可编辑,否则禁用。我们可以通过判断选中数组中是否包含「Other Contingencies」项来实现禁用逻辑。

步骤1:补充TS逻辑

首先初始化选中数组,新增辅助判断方法,修改后的TS代码如下:

// 初始化选中数组
selectedContingencies: any[] = [];

contingencies = [
  {id: 1, text: 'Financing Contigency'},
  {id: 2, text: 'Site Plan Approval Contigency'},
  {id: 3, text: 'Permit Approval Contingency'},
  {id: 4, text: 'Tenant Approval Contingency'},
  {id: 5, text: 'Other Contingencies'},
]

// 新增:判断Other Contingencies是否被选中
get isOtherChecked(): boolean {
  return this.selectedContingencies.some(item => item.id === 5)
}

changeCurrentContingencies(e:any,rowData:any){   
  if(e.checked){
    this.selectedContingencies.push(rowData);
  }else {
    this.removeSelectedContingency(rowData);
  }
}

// 补充移除选中项逻辑,如果已有可以忽略
removeSelectedContingency(rowData: any) {
  const index = this.selectedContingencies.findIndex(item => item.id === rowData.id)
  if (index > -1) {
    this.selectedContingencies.splice(index, 1)
  }
}

步骤2:修改HTML绑定

给输入框绑定disabled属性,同时建议给mat-checkbox补充checked绑定避免状态不同步问题,修改后的HTML代码如下:

<ul>
  <li *ngFor="let contigency of contingencies">
    <mat-checkbox 
    class="checkbox-margin"
    color="primary"
    [checked]="selectedContingencies.some(item => item.id === contigency.id)"
    (change)="changeCurrentContingencies($event,contigency)"
    >
    <mat-form-field  appearance="fill"  *ngIf="contigency.text === 'Other Contingencies'; else text" matInput>
      <mat-label>{{contigency.text}}</mat-label>
      <input 
        [disabled]="!isOtherChecked"
        name = "otherContingency"
        matInput
        [(ngModel)]="dealDispositionFormFields.otherContingency"
        >
        <span matPrefix *ngIf="dealDispositionFormFields.otherContingency">$</span>
    </mat-form-field>
    <ng-template #text>
    {{contigency.text}}
    </ng-template>
    </mat-checkbox>      
  </li>
</ul>

如果不想新增TS判断方法,也可以直接在模板里写绑定逻辑:[disabled]="!selectedContingencies.some(item => item.id ===5),效果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:06:04