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

Angular中选中某ng-select下拉框时如何重置其余ng-select选项

功能实现步骤

1. 调整模板事件绑定

给每个ng-select的change事件传入当前下拉框对应的formControlName值,修改后代码如下:

<ng-select id="selectOne" formControlName="name1" (change)="resetOtherSelects('name1')">
   <ng-option *ngFor = "let x of y" [value]="somevalue">{{somevalue}}</ng-option>
</ng-select>

<ng-select id="selectTwo" formControlName="name2" (change)="resetOtherSelects('name2')">
   <ng-option *ngFor = "let x of y" [value]="somevalue">{{somevalue}}</ng-option>
</ng-select>

<ng-select id="selectThree" formControlName="name3" (change)="resetOtherSelects('name3')">
    <ng-option *ngFor = "let x of y" [value]="somevalue">{{somevalue}}</ng-option>
</ng-select>

2. 编写TS逻辑代码

在对应组件的TS文件中编写清空其余下拉框的逻辑,假设你的响应式表单实例命名为searchForm,代码如下:

// 已配置响应式表单可忽略该引入
import { FormGroup, FormControl } from '@angular/forms';

// 组件内已有表单实例,可根据你的实际命名调整
searchForm: FormGroup = new FormGroup({
  name1: new FormControl(null),
  name2: new FormControl(null),
  name3: new FormControl(null)
});

// 清空其余下拉框的核心方法
resetOtherSelects(activeControl: string): void {
  // 所有关联下拉框的control名集合,新增同逻辑下拉框只需在此处加对应name即可
  const allControls = ['name1', 'name2', 'name3'];
  // 过滤出需要重置的控件
  const needResetControls = allControls.filter(item => item !== activeControl);
  // 遍历执行重置
  needResetControls.forEach(controlName => {
    this.searchForm.get(controlName)?.reset();
    // 若reset不符合业务场景,可直接赋值为null:
    // this.searchForm.get(controlName)?.setValue(null);
  })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 17:06:01