当人们选择邮政编码时,我已经实现了该功能,然后该名称将如图所示。问题是当我提交表单时,我没有看到捕获的邮政编码名称,如下面的控制台日志所示。关于如何解决此问题的任何想法?
用户界面 控制台日志 <mat-form-field>
<mat-label>Postal Code</mat-label>
<!-- <input matInput formControlName="businessPostalCode" required> -->
<mat-select formControlName="businessPostalCode" [(value)]="selected" (selectionChange)="onSelectionPostalCodeChange($event.value)">
<mat-option *ngFor="let postalcode of postalcodes" [value]="postalcode.code">
{{postalcode.code}}
</mat-option>
</mat-select>
<mat-error>This field is required</mat-error>
</mat-form-field>
<mat-form-field>
<mat-label>Postal Code Name</mat-label>
<input matInput formControlName="businessPostalCodeName" [value] ="postalcode" required>
<mat-error>This field is required</mat-error>
</mat-form-field>
TS文件
this.businessRegisterformGroup = this._formBuilder.group({
formArray: this._formBuilder.array([
this._formBuilder.group({
businessName: ['', Validators.required],
businessSize: ['', Validators.required],
numberOfEmployees: ['', Validators.required],
kraPinNumber: ['', Validators.required],
vatNumber: ['', Validators.required],
businessPhoneNumber: ['', Validators.required],
businessOtherNumber: ['', Validators.required],
businessEmail: ['', Validators.required],
businessFaxNumber: ['', Validators.required],
businessPoBoxNumber: ['', Validators.required],
businessPostalCode: ['', Validators.required],
businessPostalCodeName: ['', Validators.required],
businessTown: ['', Validators.required],
businessSubCounty: ['', Validators.required],
businessWard: ['', Validators.required],
}),
**..........**
onSelectionPostalCodeChange(e) {
this.postalCodeNumber = e;
// console.log(e);
const res = this.postalCodeDetail(e);
const c = this.businessRegisterformGroup.patchValue({
businessPostalCodeName: res
});
}
postalCodeDetail(code) {
this.apiPostalCodeDetail.getPostalCodeDetail(code)
.subscribe(res => {
this.postalcode = res.name;
// console.log(res);
});
}
答案 0 :(得分:1)
您应该使用ngModel作为邮政编码名称的值
<input matInput formControlName="businessPostalCodeName" [(ngModel)]="postalcode" required>
此外,您可能需要JSON.parse getPostalCodeDetail调用的响应
this.apiPostalCodeDetail.getPostalCodeDetail(code)
.subscribe(res => {
// export an interface with the same structure and typings as the response
this.exportedInterface = JSON.parse(res);
this.postalcode = this.exportedInterface.name;
// console.log(res);
});
导出接口或使用与您希望接收的数据具有相同结构的类是一个很好的主意。这将使您更可靠地访问返回的数据。另外,大约有99%的时间收到api响应时,它将在旅途中被字符串化,因此我假设您需要将返回的字符串转换为实际的对象或数组。
我希望这会有所帮助。