gpt4 book ai didi

html - 使用来自 API 调用的数据在子组件中设置 HTML 选择的默认值

转载 作者:搜寻专家 更新时间:2023-10-30 21:57:48 25 4
gpt4 key购买 nike

我有一个多组件表单,我想用来自 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>

子组件.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 信息:

Angular CLI: 6.0.8
Node: 8.11.2
OS: win32 x64

编辑子组件.ts

isSelected(reasonCode) {
if (reasonCode == this.rc) {
return reasonCode
}
}

最佳答案

您缺少对选定选项 ( see here) 的 selected 的绑定(bind)。您可以使用 react 形式设置选择的值,但这实际上并没有选择一个选项。

换句话说,您需要在 option 中添加类似 [selected]="isSelected(reasonCode)" 的内容:

<option *ngFor="let reasonCode of reasonCodesService.reasonCodes" [selected]="isSelected(reasonCode)">
{{reasonCode}}
</option>

例如,您可以通过将其参数与从 FormGroup 引用中获得的值进行比较来实现 isSelected

关于html - 使用来自 API 调用的数据在子组件中设置 HTML 选择的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51564896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com