【发布时间】:2021-07-23 15:02:18
【问题描述】:
我创建了一个表单,其中填充了除下拉列表之外的所有字段
async initForm() {
this.discpForm = this.formBuilder.group({
action: ["", [Validators.required]],
...
status: ["In Progress", [Validators.required]], // In Progress, Voided, Closed
// more items, offense items, evaluator,
offenses: this.formBuilder.array([]),
evaluators: this.formBuilder.array([]),
})
// fetch offense defns, fetch all users
Promise.all([
... series of DB fetch
this.afStore.doc(`/clients/${this.clientCode}/Performance/OffenseDefns`)
.ref
.get()
.then(res => {
if (res.exists) {
let offenses = res.data()
Object.keys(offenses).forEach(k => {
this.optOffenses.push({ label: offenses[k].descr, value: k })
})
}
})
])
}
我用红色箭头突出显示了错误。这些是从我的数据库中获取的字段。没有任何控制台错误。
async initDetails() {
this.initForm()
// populate data
this.discpForm.patchValue(this.discpDoc)
this.discpForm.get('reportedDate').setValue(new Date(this.discpDoc.reportedDate.seconds * 1000))
// ...
this.discpDoc.offenses.forEach(e => {
this.addOffense(e)
})
}
offenses(): FormArray {
return this.discpForm.get('offenses') as FormArray
}
newOffense(data: any = {}): FormGroup {
return this.formBuilder.group({
offense: [data.hasOwnProperty('offense') ? data.offense : '', [Validators.required]],
reportedDate: [data.hasOwnProperty('reportedDate') ? new Date(data.reportedDate.seconds * 1000) : '', [Validators.required]],
reportedBy: [data.hasOwnProperty('reportedBy') ? data.reportedBy : '', [Validators.required]],
})
}
addOffense(data: any) {
this.offenses().push(this.newOffense(data))
}
模板逻辑,它应该填充文本字段、日期字段、下拉列表,作为逻辑推送通过patchValue和通过方法'newOffense()'分配的值列表
<div class="p-field p-col-3 _float-ui-spacing_">
<span class="p-float-label">
<p-dropdown [options]="optOffenses" formControlName="offense">
</p-dropdown>
<p-message severity="error" text="Offense Code is required"
*ngIf="!item.get('offense').valid&&item.get('offense').dirty">
</p-message>
<label>Offense</label>
</span>
</div>
【问题讨论】:
-
我想你可以阅读这个表单数组:netbasal.com/…
-
我不知道您的
optOffenses数组,但请注意,如果是对象数组(不是简单的字符串数组),您需要使用optionValue,请参阅 p -dropdown:primefaces.org/primeng/showcase/#/dropdown. -
@Eliseo - 感谢您的示例代码。我更改了我的流程以获取数据库的设置并在construct() {} 部分填充值(消耗更多的数据库获取资源,每次刷新组件时都获取,但总比不正确填充好)