Angular父组件中共用下拉组件选中值被覆盖该如何解决?
问题根因
你当前的问题核心是两个逻辑错误叠加导致的:
- 所有下拉组件共用同一个无分类标识的Subject,国家、货币的选中事件没有做区分,全部覆盖到了
countrySelected变量 - 右侧货币备用下拉的
alternateDropDownCode错误绑定了countrySelected变量,而非货币自身的选中值
解决方案
按以下步骤调整代码即可解决:
步骤1:调整下拉组件的事件发射逻辑,新增类型标识
修改通用下拉组件的select方法,发射选中值时同步传递ref属性标识当前下拉的类型:
select(option: string) { if (!this.disabled) { this.value = option; // 传递ref和选中值,方便订阅端区分类型 this.kycService.countrySeletion$.next({ ref: this.ref, value: option }); this.onChanged(option); this.onTouched(); } }
步骤2:父组件新增货币选中存储变量,分类处理订阅结果
在父组件ts文件中新增currencySelected变量,订阅时根据ref值分别赋值:
// 新增变量存储货币选中值 countrySelected: string; currencySelected: string; constructor(private formBuilder: FormBuilder, private kycService: KycService) { super(); this.id = 'BANK_DETAILS'; this.kycService.countrySeletion$.subscribe((res: any) => { if(res.ref === 'countries') { // 国家类型赋值给国家变量 this.countrySelected = res.value; } else if(res.ref === 'currencies') { // 货币类型赋值给货币变量 this.currencySelected = res.value; } }); }
步骤3:修正父组件模板的绑定错误
将右侧货币下拉的alternateDropDownCode绑定值从countrySelected改为currencySelected:
<div class="field"> <label for="alternateBankCurrency" translate> common.currency </label> <app-ref-select [ngClass]="{ submitted: submitted }" formControlName="alternateBankCurrency" [showAlternateDropDown]="accounts.controls[i].get('yesNoMultilingual')?.value" <!-- 这里替换为货币选中值 --> [alternateDropDownCode]="currencySelected" name="alternateBankCurrency" id="alternateBankCurrency" ref="currencies" enableTranslation="true"> </app-ref-select> </div>
可选优化方案
如果后续需要扩展更多类型的下拉,也可以直接在Service中拆分独立Subject,逻辑更清晰耦合更低:
- 修改KycService:
// 拆分国家、货币两个独立Subject countrySeletion$ = new Subject<string>(); currencySelection$ = new Subject<string>();
- 修改下拉组件select方法,根据ref发射到对应Subject:
select(option: string) { if (!this.disabled) { this.value = option; if(this.ref === 'countries') { this.kycService.countrySeletion$.next(option); } else if(this.ref === 'currencies') { this.kycService.currencySelection$.next(option); } this.onChanged(option); this.onTouched(); } }
- 父组件分别订阅两个Subject:
this.kycService.countrySeletion$.subscribe(res => this.countrySelected = res); this.kycService.currencySelection$.subscribe(res => this.currencySelected = res);
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

