首页 > 解决方案 > 角度绑定问题 - 段落不更新

问题描述

收到来自外部 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(地址)检索数据时,表单中的值不会更改。有谁知道如何解决这个问题?

标签: angular

解决方案


首先,在您的 html 中,您有 onSubmit 方法,但在打字稿中我看到 onLocateAddress(),我假设这只是发布问题时的一个错误。其次,你的意思是,它没有更新

<p>{{ locatedAddress }}</p>

还是在您的表单输入中?

应更新locatedAddress。表单输入可能没有更新,因为您没有将返回的结果绑定到表单中 ngModel 绑定的值。您正在将值传递给未绑定到表单输入的 locateAddress 对象


推荐阅读