angular - Angular 6反应形式选择组件未从patchValue中选择选项
问题描述
我正在将选择元素包装为select-ddl
具有附加功能的组件(称为 )。在我发现调用 setValue 或 patchValue 时 FormGroup 没有自动选择正确的选项之前,我没有考虑“附加功能”。
对我来说真正没有意义的是验证正在工作,如果我在下拉列表中选择一个值,调用this.form.value
将返回正确的结果并companyId
设置。我相信这意味着SelectControlValueAccessor
Angular 正在正确设置将 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)如何让它按照设计的方式工作。
解决方案
推荐阅读
- sockets - 如何在聚合物 3 PWA 入门套件应用程序中导入 socket.io.client javascript 以进行服务器构建
- python - 我应该提出自定义异常吗?
- php - 使用 PHP 中的 files.upload 将文件上传到 slack
- r - R GRMetric:如何个性化情节设计(主题、颜色、图例等)
- assembly - 计算数字的平方并将它们存储在装配 8086 masm 中的 dw 中
- vba - 在 VBA 中的评论中添加 URL 链接
- c++ - 从字符串流(和布尔类型)中提取值后的 rdstate()
- html - 纯css表格固定标题和数据可在浏览器中滚动
- python-3.x - 操作系统使用 3.7 时使用 Python 3.6
- css - 将左浮动元素定位在页面的中心