我正在以这种方式初始化我的表单,但是当我需要编辑它时,它不接受这些值
组件.ts
ngOnInit() {
this.tinvoiceService.initForm();
}
tinvoice.service.ts
form: FormGroup;
constructor(
private _fb: FormBuilder,
private invoiceService: InvoiceService
) {}
initForm(): void {
this.form = this._fb.group({
customer: [null, Validators.required],
totalPrice: 0,
purchases: this._fb.array([])
});
// initialize stream
const myFormValueChanges$ = this.form.controls['purchases'].valueChanges;
myFormValueChanges$.subscribe(purchases => this.updatePurchasesAmount(purchases));
}
我从 HTML 传递值
tinvoice.component.html
<a
class="btn btn-outline-info text-info"
(click)="tinvoiceService.populateForm(invoice)">
Edit
</a>
tinvoice-list.component.ts
populateForm(invoice) {
this.form.setValue(invoice);
}
通过控制台我得到这个结果
有什么想法吗?
Form 是一个 UI 元素,它在视图渲染后被实例化。
你可以尝试在
ngAfterViewInit
中调用这个函数,错误应该消失了。如果不只是创建一个小提琴,我会尽力为您修复它。
老问题,但会给出我的看法
当用户单击编辑按钮时,控制台日志工作指示
找不到名称为:购买的表单控件
所以我们从这里开始并找出该行中的问题
this.form.setValue(invoice)
如果我们此时记录
invoice
的值,我们会看到
{
"createdAt": "Mon May 10 2021 15:32:51 GMT+0100 (UTC+01:00)",
"customer": {
"address": "s",
"lastname": "Perez",
"name": "Carlos ",
"phone": "7861236589"
},
"purchases": [
{
"product": {
"categoryS": "-MZyCBHUjLrfxzoRdZBM",
"location": "Store",
"name": "TV Samsung",
"price": 50
},
"quantity": 1
}
],
"totalPrice": 50,
"$key": "-M_LgTlysUg07lHdjtuG"
}
如果我们记录
this.form.value
的值,我们 aee
{
"customer": {
"name": null,
"lastname": null,
"address": null,
"phone": null
},
"createdAt": null
}
因此,您正在尝试为表单分配不正确的对象结构。
要检查您的代码是否确实有效,您只需将
setValue
更改为 patchValue
。以下解决方案的工作原理是,与 patchValue
不同,setValue
只会查找仅存在的表单控件。另一方面,要使用 setValue
,您必须确保对象中的所有属性都在 FormGroup 中表示,否则从对象中删除这些属性
下面是一个 Demo,展示了通过将
setValue
更改为 patchValue
的解决方案