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

Angular循环生成的无标签mat-checkbox选中时如何显示相邻文本框

TS 代码修改

首先给每个选项增加选中状态标识,同步修改状态更新逻辑:

export class DealIdleDispositionComponent implements OnInit {
  // 每个选项新增checked字段记录选中状态
  contingencies = [
    {id: 1, text: 'Financing Contigency', checked: false},
    {id: 2, text: 'Site Approval Contigency', checked: false},
    {id: 3, text: 'Permit Approval Contingency', checked: false},
    {id: 4, text: 'Tenant Approval Contingency', checked: false},
    {id: 5, text: '', checked: false},
  ]

  changeCurrentContingencies(event: MatCheckboxChange, contigency: any) {
    // 同步更新当前选项的选中状态
    contigency.checked = event.checked;
    // 原有业务逻辑保留即可
  }
  ......
}

HTML 代码修改

调整输入框的位置和显示条件,避免点击输入框误触发checkbox状态切换:

<div class="deal-disposition-row"></div>     
<div class="pharmacy-checkbox">
  <mat-checkbox
   color="primary"
   style="margin-left:10px;"
   name="isAnyContingencies"
   [(ngModel)]="dealDispositionFormFields.isAnyContingencies"
    >
   <div class="deal-text-label">
    Any Contingencies?
  </div>
  </mat-checkbox>
</div>
<span>
  <ul>
    <li *ngFor="let contigency of contingencies" style="display: flex; align-items: center; gap: 8px; margin: 4px 0;">
      <mat-checkbox 
      class="checkbox-margin"
      color="primary"
      [checked]="contigency.checked"
      (change)="changeCurrentContingencies($event,contigency)"
      >
        {{contigency.text}}
      </mat-checkbox>
      <!-- 仅无标签且被选中时显示输入框 -->
      <mat-form-field appearance="fill" *ngIf="!contigency.text && contigency.checked" style="width: 220px; margin: 0;">
        <mat-label>Other Contingencies</mat-label>
        <input 
          name="buyerProposedPlans"
          matInput
          [(ngModel)]="dealDispositionFormFields.buyerProposedPlans"
          >
          <span matPrefix *ngIf="dealDispositionFormFields.salePrice">$</span>
      </mat-form-field>
    </li>
  </ul>
</span>
</div>

逻辑说明

  • 每个选项独立存储选中状态,不会和其他选项的状态混淆
  • 输入框新增选中状态判断,只有无预设文本的特殊选项被勾选时才会展示
  • 输入框挪到checkbox外部,避免点击输入区域误切换checkbox选中状态
  • 有预设文本的选项逻辑和原有实现完全一致,不需要额外调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:24:08