如何在typescript中显示对象值



如何在angular中显示表单中的对象值。在浏览器开发人员工具,我得到的对象和它的值很好。但是不能填充表单中的值。

*。我得到的文件是:

console.log(this.product),              // {"productId": "3", "productName": "G500 cpu", "productDescription": "gaming computer", "productCategory": "computers", "units": 5 }
this.updateForm.patchValue({
// productId: '23128',                // display 23128
//   productName: 'asdas',            // display asdas
productId: this.product.productId,    // doesnt display anything
productName: this.product.productName // doesnt display anything
// productId: this.product,    // display [object Object]
// productName: this.product // display [object Object]
})

in *.html I got:

<form [formGroup]="updateForm">
<div class="form-group">
<input
type="text"
class="form-control"
formControlName="productId">
</div>
<div class="form-group">
<input
type="text"
class="form-control"
formControlName="productName"
/>
</div>

不为每个控件赋值patch为产品对象的整个值,只需确保表单控件名称和对象变量名称应该匹配。

stackblitz例子

this.updateForm = this.formBuilder.group({
productId: new FormControl(''),
productName: new FormControl(''),
productDescription: new FormControl(''),
productCategory: new FormControl(''),
units: new FormControl('')
});

var product = {
productId: "3",
productName: "G500 cpu",
productDescription: "gaming computer",
productCategory: "computers",
units: 5 
};
this.updateForm.patchValue(product);

最新更新