首页 > 解决方案 > Angular 6反应形式选择组件未从patchValue中选择选项

问题描述

我正在将选择元素包装为select-ddl具有附加功能的组件(称为 )。在我发现调用 setValue 或 patchValue 时 FormGroup 没有自动选择正确的选项之前,我没有考虑“附加功能”。

对我来说真正没有意义的是验证正在工作,如果我在下拉列表中选择一个值,调用this.form.value将返回正确的结果并companyId设置。我相信这意味着SelectControlValueAccessorAngular 正在正确设置将 FormControl 连接到 DOM 元素。

person-edit.component.ts 包含:

id = 0;
form: FormGroup;
record: PersonViewModel = new PersonViewModel();
companies: NameViewModel[] | undefined;

constructor(
  private dataService: PeopleService,
  private route: ActivatedRoute,
  private fb: FormBuilder) {
  this.form = this.fb.group({ companyId: [null, [Validators.required]] });
}

ngOnInit() {
  this.route.params.subscribe((params) => {
    this.id = Number(params.id)
    this.dataService.getRecord(this.id).subscribe(result => {
        this.record = result;
        this.form.patchValue(this.record);
      });
  this.dataService.getCompanies().subscribe(result => this.companies = result);
}

person-edit.component.html 包含:

<select select-ddl id="companyIdInput" formControlName="companyId" [items]="companies"></select>

select-ddl.component.html 包含:

@Component({
  selector: "select[select-ddl]",
  template: `<option *ngFor="let item of items" value="{{item.id}}">{{item.name}}</option>`,
})
export class SelectDdlComponent implements OnChanges {
  @Input() items: NameViewModel[] | undefined;
}

我注意到的一件事是,公司在记录之后列出负载。因此,在表单上已经调用了 patchValue 之后,正在创建选项。当它只是 person-edit.component 中的普通选择时,这不是问题,但现在我使用的是 new select-ddl,它已经坏了。此外,如果我强迫公司在记录之前加载,问题就会消失。

在 this.companies 设置之后,我尝试this.form.get("companyId")!.setValue(this.record.companyId)在语句中调用。getCompanies().subscribe它没有帮助。但是,当时还没有异步创建选项元素,所以我预料到了。

this.record.companyId我可以通过将作为输入传递给 select-ddl,然后将其放在选项元素上来解决该问题: [attr.selected]="item.id === itemId ? '' : null". 但这是一个 hack,我希望它能够使用内置的引擎盖下的工具无缝地正常工作。

更新:我有理由确定该问题与NgSelectOption指令有关,该指令似乎将选项绑定到选择以完全解决此需求。但是,我不知道(a)如何诊断为什么它在这种情况下不起作用,或者(b)如何让它按照设计的方式工作。

标签: angularangular6angular-reactive-forms

解决方案


推荐阅读