更改后,Angular 2不会更新视图

时间:2017-03-28 09:00:27

标签: javascript google-maps angular

给定以下Angular 2代码查找当前位置并转换为人类可读字符串 - >绑定到输入元素:

html tempalte:

<input name="myAddr" [(ngModel)]="form.address" type="text">
<button (click)="findMyLocation()" class="ui location right blue icon button">
  <i class="marker icon"></i>
</button>

Angular 2代码:

form: {
    volume: number,
    thickness: number,
    density: number,
    address: string
  } = { address: '', volume: 0, thickness: 100, density: 300 };

findMyLocation(){
    $('.location').addClass('loading');
    navigator.geolocation.getCurrentPosition(position => {
      this.geocoder.geocode({location: { lat: position.coords.latitude, lng: position.coords.longitude }}, (results, status)=>{
        if(status == 'OK')
          if(results[0]){
            $('.location').removeClass('loading');
            console.log('Addr: ' + results[0].formatted_address);
            this.form.address = results[0].formatted_address;
          }
      })
    }, fail => {
      console.log(fail);
    });
  }

然而,当我点击按钮时,位置(lat,lng)被转换为humar可读地址,我可以看到输出到控制台。但输入元素不会改变。如果我再次单击按钮,元素将按原样进行更新。 怎么样? Screen-1, Clciked Screen-2, clicked twice

1 个答案:

答案 0 :(得分:2)

Bacause navigator.geolocation.getCurrentPosition是异步函数,你必须使用ngZone.run让角度重新渲染模型。

this.ngZone.run(function() {
  this.form.address = results[0].formatted_address;
};)

注意:您必须在构造函数中导入NgZoneinject

UPD:我知道有两种方式:

  • ngZone.run()
  • ChangeDetectorRef.detectChanges()