Angular/PrimeNG绑定对象到输入框显示[object object]的解决方法
Angular表单绑定对象到输入框显示[Object Object]的问题与解决方法
问题场景
在Angular中绑定对象到输入框时,输入框显示[Object Object],需求是仅展示对象中的tenantLegalName字段。相关代码如下:
初始输入框代码:
<input formControlName="tenantLegalNameId" type="text" pInputText [required]="true" [style]="{'width':'100%'}"/>
表单控件定义:
testform = new FormGroup({ // 其他无问题的表单控件... tenantLegalNameId: new FormControl({ value: "", disabled: true }, [ Validators.required, ]), // 其他无问题的表单控件... })
通过patchValue为tenantLegalNameId绑定对象:
this.stationInfoForm.patchValue({ tenantLegalNameId: { tenantId: this.stationInfo?.tenantLegalNameId, tenantLegalName: this.stationInfo?.tenantLegalName, }, stateId: this.stationInfo?.stateId, typeOfEntity: this.stationInfo?.typeOfEntity, stationCallLetters: this.stationInfo?.stationCallLetters, stationFrequency: this.stationInfo?.stationFrequency, });
尝试过的无效方法
方式一
直接在formControlName中使用对象路径:
<form [formGroup]="testform"> <!-- 其他正常输入框... --> <input formControlName="tenantLegalNameId?.tenantLegalName" type="text" pInputText [required]="true" [style]="{'width':'100%'}"/> <!-- 其他正常输入框... --> </form>
方式二
通过[value]手动指定字段值:
<input formControlName="tenantLegalNameId" [value]="testform.get('tenantLegalNameId').tenantLegalName" type="text" pInputText [required]="true" [style]="{'width':'100%'}"/>
解决方案
将tenantLegalNameId改为FormGroup类型,定义getGroup方法返回嵌套表单组:
this.stationInfoForm = new FormGroup({ // 注释原FormControl定义 // tenantLegalNameId: new FormControl({ value: "", disabled: true }, [ // Validators.required, // ]), tenantLegalNameId: this.getGroup(), // 其他表单控件... })
getGroup方法实现:
getGroup() { return this.formBuilder.group({ tenantId: this.stationInfo?.tenantLegalNameId, tenantLegalName: this.stationInfo?.tenantLegalName, relationshipName: '' }) }
UI层通过div包裹输入框并设置formGroupName为tenantLegalNameId,输入框的formControlName设为tenantLegalName:
<div class="col-6" formGroupName="tenantLegalNameId"> <label for="tenantLegalNameId">Tenant Legal Name *</label> <input formControlName="tenantLegalName" type="text" pInputText [required]="true" [style]="{'width':'100%'}"/> <small class="p-error" *ngIf="tenantLegalNameId.isTouched && tenantLegalNameId.invalid" [hidden]="true">Required Field</small> </div>
内容的提问来源于stack exchange,提问作者robtown
相关产品推荐
相关产品推荐

