我有一个多组件表单,希望预先填充来自API调用的数据。除了select
标记的选定值之外,每个字段的数据都会正确填充。value
是正确的,只是在select
中没有显示正确的option
。表单的其余部分由input
字段组成,用正确的数据填充。
子组件接受一个表单组,这是填充域的内容。
我已经尝试过.setValue
、.patchValue
、[(ngModel)]
等,但无法获得正确显示的默认值。我做错了什么?
child-component.html
<select [attr.id]="reasonCode" formControlName="reasonCode" placeholder="Reason Code" style="max-width: 100% !important"
no-padding selected>
<option value="" >Please select reason code</option>
<option *ngFor="let reasonCode of reasonCodesService.reasonCodes">
{{reasonCode}}
</option>
</select>
child-component.ts
@Input() newReqForm: FormGroup;
parent-component.html
<div *ngFor="let control of newForm.controls['requisitionItem'].controls; let i = index" style="border: 1px solid black; border-radius: 10px; margin-top: 10px;">
<edit-items (remove)='onRemove($event)' [newReqForm]="newForm.controls.requisitionItem.controls[i]" style="padding-bottom: 10px"
[index]='i'></edit-items>
</div>
parent-component.ts
ngOnInit() {
this.employeeService.loadEmployees();
this.reasonCodesService.loadReasonCodes();
this.itemReqId = +this.route.snapshot.paramMap.get('ReqId');
this.reqService.getRequisition(this.itemReqId).subscribe(response => {
this.editReq = response;
console.log("EDIT REQ VVV");
console.log(this.editReq);
this.editRI = this.editReq.requisitionItem;
this.newForm = this.fb.group({
employee: [this.editReq.employee, Validators.required],
job: [this.editReq.job, Validators.compose([Validators.pattern("^[0-9]+$")])],
requisitionItem: this.fb.array([
])
});
this.arrayControl = <FormArray>this.newForm.controls['requisitionItem'];
this.editRI.forEach(item => {
let newItem = this.fb.group({
item: [item.item, Validators.required],
quantity: [item.quantity, Validators.compose([Validators.required, Validators.pattern("^[0-9]+$")])],
reasonCode: [item.reasonCode],
operation: [item.operation],
})
this.arrayControl.push(newItem);
this.setValidators()
});
for (let i = 0; i < this.arrayControl.length; i++) {
this.arrayControl.controls[i].get('reasonCode').setValue(this.editRI[i].reasonCode);
}
this.setValidators();
console.log(this.editReq);
this.newReqForm = this.newForm;
});
}
我的节点/角度信息:
Angular CLI: 6.0.8
Node: 8.11.2
OS: win32 x64
编辑child-component.ts
isSelected(reasonCode) {
if (reasonCode == this.rc) {
return reasonCode
}
}
发布于 2018-07-28 04:33:34
缺少所选选项(see here)的selected
上的绑定。您可以使用reactive forms设置select的值,但这并不会实际选择选项。
换句话说,您需要向option
添加类似于[selected]="isSelected(reasonCode)"
的内容
<option *ngFor="let reasonCode of reasonCodesService.reasonCodes" [selected]="isSelected(reasonCode)">
{{reasonCode}}
</option>
例如,您可以通过将其参数与从FormGroup
引用中获得的值进行比较来实现isSelected
。
https://stackoverflow.com/questions/51564896
复制相似问题