angular - 角度绑定问题 - 段落不更新
问题描述
收到来自外部 API 的响应后,我想显示该值。HTML 如下所示:
<section class="signup-form">
<form fxLayout="column" fxLayoutAlign="center center" #f="ngForm" (ngSubmit)=onSubmit(f)>
<mat-form-field>
<input type="text" matInput placeholder="Label" ngModel name="label" required>
</mat-form-field>
<mat-form-field>
<input type="text" matInput placeholder="Address" ngModel name="address" required>
</mat-form-field>
<div id="btnLocate" fxFlex fxLayout fxLayoutAlign="flex-end">
<button type="submit" mat-raised-button color="primary">Locate...</button>
</div>
<div id="mapContainer" fxFlex fxLayout fxLayoutAlign="center">
<p>{{ locatedAddress }}</p>
</div>
</div>
</form>
</section>
以下是组件的定义:
export class DepotComponent implements OnInit {
locatedAddress: string = null;
constructor(private googleApiService: GoogleApiService) {
}
ngOnInit(): void {
}
onLocateAddress(form: NgForm) {
console.log(form.value.address);
this.googleApiService.getLocation(form.value.address)
.subscribe(
(response: any) => {
if (response){
if(response.status === "OK"){
const firstMatch = response.results[0];
if (firstMatch.hasOwnProperty('partial_match') && firstMatch.partial_match) {
console.log('Address not found!')
}
this.locatedAddress = firstMatch.formatted_address;
console.log(this.locatedAddress);
}
}
},
(error) => console.log(error)
);
}
当从 API(地址)检索数据时,表单中的值不会更改。有谁知道如何解决这个问题?
解决方案
首先,在您的 html 中,您有 onSubmit 方法,但在打字稿中我看到 onLocateAddress(),我假设这只是发布问题时的一个错误。其次,你的意思是,它没有更新
<p>{{ locatedAddress }}</p>
还是在您的表单输入中?
应更新locatedAddress。表单输入可能没有更新,因为您没有将返回的结果绑定到表单中 ngModel 绑定的值。您正在将值传递给未绑定到表单输入的 locateAddress 对象
推荐阅读
- csv - sphinx 上 table-csv 内的 reStructuredText 替换
- vimeo-api - 缩略图上传 - 管理规则禁止的请求
- wordpress - 使用 EC2 创建的 Wordpress 实例的 SSL 证书
- javascript - Node.js - ssh2-sftp-client 获取多个文件错误
- python - 无法使用 django 从页面发送邮件,SMTPAuthenticationError
- java - 如何进行更大数量的操作
- python - Google Cloud Run:将多个应用文件打包到一个 docker 映像中
- macos - 如何在 AzureDevops 中安装 Mac 配置文件?
- c++ - 当 x 的范围有限时,为什么 x/10 会通过不必要的移位进行优化?
- html - Python3 从网页下载图像