angular - 提交后表单中未捕获 mat-form-field 中的值
问题描述
当一个人选择邮政编码时,我已经实现了该功能,然后名称将如图所示呈现。问题是当我提交表单时,我没有看到正在捕获的邮政编码名称,如下面的控制台日志所示。有什么想法可以解决这个问题吗?
用户界面 控制台日志HTML 文件
<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);
});
}
解决方案
您应该使用 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 响应,它将为旅程进行字符串化,所以我假设你需要将返回的字符串转换为实际的对象或数组。
我希望这有帮助。
推荐阅读
- reactjs - 如何将 React 框架导入 vscode 源代码项目以创建 UI 组件?
- reactjs - 我用过这个命令 npm runeject 它不工作
- azure-web-app-service - Azure Webapp(Windows):对外部链接的 URL 重写返回错误
- bash - 在 bash 中有效获取命令输出的一致语法?
- android - 如何在 Android Studio 中通过 logcat 或终端查看 Google Analytics 测量协议(调试)
- django - django如何将上传到数据库的文件的链接和实际文件的链接保存在django的特定文件夹中
- function - Kotlin - 将 sortBy 参数作为函数参数传递
- java - 我如何使用 volley 从服务器发送和验证参数?
- python - 按元素对列表组合求和
- reactjs - 在 JSX 中定义变量