Javascript 角度2在更改值后不更新视图
给定以下Angular 2代码,查找当前位置并转换为可读字符串->绑定到输入元素: html tempalte: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>
<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()
表单
,则会在视图中看到更改。刚刚测试过,声明其他单字符串变量也不起作用:(如果我点击两次按钮,效果会很好,但这是意外行为。谢谢!效果很好。所以,每个第三方库的asyc函数都应该在ngZone内运行?@EvghenyKalkutin我已经更新了你的评论答案。因为对我来说,我总是使用第一个,相当于$scope。$apply()经常在angular1.x中使用。)
this.ngZone.run(function() {
this.form.address = results[0].formatted_address;
};)