Angular表单切换Source后Sub-Source控件视觉与FormControl值不一致
问题描述
- 表单包含Source与Sub-Source字段,每个Source对应专属的Sub-Source列表
- 切换Source时,Sub-Source下拉框视觉上自动选中第一项,但对应的FormControl对象中无选中值
- 表单要求必须手动选择Sub-Source选项才能提交,无法通过点击视觉上已“选中”的项完成选择
- 期望效果:切换Source时,Sub-Source下拉框保持空白状态
当前现象
视觉表现:Sub-Source下拉框默认显示列表第一项内容
FormControl状态:控件值为null,未绑定选中项
TS代码
onSourceSelected(target: any) { var current = this.alertSources.find(it => it.id == target) if (!current) { console.error(`Found no alert source for ID: ${target}.`); return; } this.subSourcesForAlertSource = this.getSubSourcesForSource(current.id, this.alertSources); if (this.subSourcesForAlertSource.length === 0) { this.subSource.clearValidators(); this.subSource.patchValue<string>(null); this.subSource.markAsDirty(); } else { this.subSource.setValidators(Validators.required); } this.subSource.updateValueAndValidity(); console.log(this.subSource); }
HTML代码
<div class="sm:col-span-3"> <label for="source" class="block text-sm pt-3 font-medium text-gray-700"> Source </label> <div class="mt-1"> <select id="source" name="source" formControlName="source" class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md" (change)="onSourceSelected($event.target.value)"> <option *ngFor="let source of alertSources" value="{{source.id}}">{{source.name}}</option> </select> </div> </div> <div class="sm:col-span-3" *ngIf="subSourcesForAlertSource.length > 0"> <label for="subsource" class="block text-sm pt-3 font-medium text-gray-700"> Sub-source </label> <div class="mt-1"> <select id="subsource" name="subsource" formControlName="subsource" class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md"> <ng-container *ngFor="let subSource of subSourcesForAlertSource"> <option *ngIf="!subSource.isDisabled || subSource.id === alert?.subSource?.id" [disabled]="subSource.isDisabled" [hidden]="subSource.isDisabled" value="{{subSource.id}}"> {{subSource.isDisabled ? subSource.name + " [DISABLED]" : subSource.name}} </option> </ng-container> </select> <div *ngIf="subSource.invalid && (subSource.dirty || subSource.touched || source.dirty || source.touched)" class="text-red-600 text-sm"> Sub-source is required. </div> </div> </div>
已尝试方案
- 使用
reset()、setValue(null)等方法重置Sub-Source的FormControl,问题未解决
内容的提问来源于stack exchange,提问作者Andrew Sabee
相关产品推荐
相关产品推荐

