javascript - PatchValue 或 setValue 与 formGroup 更多 formArray 和 formGroup
问题描述
我有第二种形式。我需要在字段中填写来自银行的日期,一个 json 文件。在该populateFields
方法中,我得到一个参数,其中包含将要填充的数据。但是,它只填充itens
数组内部的 , description 的值,它不执行。
错误:
ERROR 错误:未捕获(承诺中):TypeError:_this.form.controls.itens.value [i] .description.patchValue 不是函数
我尝试使用以下表达式:
this.form.controls.itens.value[i].description.patchValue(item.description);
但是,我收到上面提到的错误。
generateFormGroup(): void {
this.form = this._formBuilder.group({
id: [null],
alias: ['Relatório de Despesa', [Validators.required, Validators.maxLength(50)]],
job: [null, [Validators.required]],
customer: [{ value: null, disabled: true }, [Validators.required]],
contact: [{ value: null, disabled: true }, [Validators.required]],
currency: [{ value: 1, disabled: true }, [Validators.required]],
exchangeRate: [{ value: null, disabled: true }],
advanceValue: ['0'],
itens: this._formBuilder.array([this.createItem()]),
});
}
createItem(): any {
return this._formBuilder.group({
id: [null],
product: [null, [Validators.required]],
productIcon: [null],
description: this._formBuilder.group({
descriptionProduct: [null],
origin: [null],
km: [null],
destination: [null],
rental: [null],
days: [null],
reason: [null],
taglist: [null]
}),
date: [this.today, [Validators.required]],
value: [0, [Validators.required, Validators.min(0.01)]],
currency: [{ value: 1, disabled: true }, [Validators.required]],
currencyAlias: [this.currency],
receipt: [null],
isLoading: [false],
receiptId: [null],
receiptExtension: [null],
});
}
populateFields(data: any): void {
data.itens.forEach((item, i) => {
this.form.controls.itens.value [i] .description.patchValue (item.description) // error
}
this.itens = data.itens;
this.form.controls.itens.patchValue(data.itens);
}
解决方案
this.form['controls']['itens']['controls'][index]['controls'].description.patchValue(item.description);
更新:
我使用访问属性的方括号表示法来抑制错误,例如Property 'controls' does not exist on type 'AbstractControl'
你可以在这个 Github 页面上阅读更多关于它的信息
仅当您有多个级别的表单控件时,这才是一个问题。如果您有直截了当的内容,则可以使用.
符号甚至.get()
方法来访问控件
this.form.controls.someControl.patchValue(someValue)
this.form.get('someControl').patchValue(someValue)
上面两个做同样的事情。如果是简单的表单数组,可以使用.at()
方法
结合这些并做一些类型转换,你可以做这样的事情
((this.form.get('controls') as FormArray).at(index) as FormGroup).get('description').patchValue(item.description);
从理论上讲,以上应该有效:)
推荐阅读
- python - 通过 lambda 发送的 AWS Open 搜索请求超时
- docker - Kuberetes traefik 控制器中的 ROOT 和中间 SSL 证书配置
- typescript - aws cdk typescript issue type='CNAME'] 但它已经存在]
- c# - 使用 JsonConvert.SerializeObject 在序列化期间本地化属性
- javascript - 如何在地图数组中单独检查复选框?
- google-bigquery - BigQuery Data Transfer Service 支持 AVRO 的逻辑类型?
- php - Laravel Nova Admin 中 Nova 类的可重用性
- javascript - 反应 useStyles 不应用样式
- php - 有没有 Laravel 关系可以匹配这种遥远的关系?
- bash - 包括文件内容的路径