Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 角度2在更改值后不更新视图_Javascript_Google Maps_Angular - Fatal编程技术网

Javascript 角度2在更改值后不更新视图

Javascript 角度2在更改值后不更新视图,javascript,google-maps,angular,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>

给定以下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>
然而,当我点击按钮时,位置(lat,lng)被转换成humar可读地址,我可以看到控制台的输出。但输入元素并没有改变。若我再次单击按钮,元素将按原样更新。 伙计们,怎么了?

因为navigator.geolocation.getCurrentPosition是异步函数,您必须使用ngZone.run让angular重新启动模型

this.ngZone.run(function() {
  this.form.address = results[0].formatted_address;
};)
注意:您必须在构造函数中导入
NgZone
inject

UPD:据我所知,有两种方式:

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

据我所知,Angular不观察对象属性的变化,只观察对象本身(其引用)。如果用新对象替换
表单
,则会在视图中看到更改。刚刚测试过,声明其他单字符串变量也不起作用:(如果我点击两次按钮,效果会很好,但这是意外行为。谢谢!效果很好。所以,每个第三方库的asyc函数都应该在ngZone内运行?@EvghenyKalkutin我已经更新了你的评论答案。因为对我来说,我总是使用第一个,相当于$scope。$apply()经常在angular1.x中使用。)
this.ngZone.run(function() {
  this.form.address = results[0].formatted_address;
};)