【问题标题】:ngModel updates in controller, but not in the view, angular 2ngModel 在控制器中更新,但不在视图中,角度 2
【发布时间】:2016-01-15 10:12:29
【问题描述】:

我有一个意见:

  <label for="map-latitude_input">Latitude {{mapLatitudeInput}}</label>
  <input
    type="text"
    placeholder="00.000"
    [(ngModel)]="mapLatitudeInput"
    [ngFormControl]="newListingForm.find('mapLatitudeInput')"
    id="map-latitude_input"
    class="transparent">

在我的控制器内部,我正在收听来自 google maps api 的地图拖动事件。在拖动时,我想更新我的输入及其相关标签中的值。目前看起来是这样的:

//Update coordinates on map drag
map.addListener('drag', (event) => {
  this.mapLatitudeInput = map.getCenter().lat();
  console.log(this.mapLatitudeInput);
});

现在,当我拖动地图控制台时,我在移动它时不断输出正确的值,但在我看来,它保持完全相同。我还注意到,如果我拖动地图而不是执行一些操作,例如在与我的输入相同的表单中的选择菜单中选择一个选项,它会将mapLatitudeInput 更新为正确的值,我不确定为什么会发生这种情况,但我想我会提到它。

【问题讨论】:

  • 我假设map.getCenter().lat(); 每次都返回相同的对象,但只有更新的值。您可以通过将返回的值与前一个值进行比较来验证这一点。
  • @GünterZöchbauer 让我感到困惑的是,在控制台中打印 this.mapLatitudeInput 实际上表明它正在按我的预期进行更新,但是它不会反映在视图输入中,除非我这样做,否则它的值保持不变表单中的其他操作,即开始输入另一个输入或其他内容。你认为这可能是角度 2 中的错误吗?
  • 您的问题没有提供足够的信息。这也可能是@thierrytemplier 在他的回答中解释的区域问题。

标签: javascript google-maps google-maps-api-3 angular


【解决方案1】:

这可能是由于 ZoneJS。这个问题可以给你一些提示:View is not updated on change in Angular2.

您从哪里获得地图实例。如果在区域外实例化,Angular2 将无法检测到mapLatitudeInput 属性的更新。

你可以试试这样的:

export class MapComponent {
  constructor(ngZone:NgZone) {
    this.ngZone = ngZone;
  }

  map.addListener('drag', (event) => {
    this.ngZone.run(() =>
      this.mapLatitudeInput = map.getCenter().lat();
      console.log(this.mapLatitudeInput);
    });
  });

这个问题也可能与您的问题有关:Angular2 child property change not firing update on bound property

希望对你有帮助 蒂埃里

【讨论】:

  • 它是angular2/core 的一部分。请参阅此链接:angular.io/docs/ts/latest/api/core/NgZone-class.html。只需导入它并将其用作构造函数参数...
  • 你是杰出的帮助,非常感谢你的回答,它真的帮助我学习 Angular 2。
  • 此外,您还可以阅读 Mark Rajcok 在 ZoneJS / Angular2 上的精彩回答:stackoverflow.com/questions/34569094/… ;-)
  • 这个周末我会阅读很多关于 Angular 2 的内容,这是肯定的。刚刚跳上它做一个测试项目,看看我是否喜欢它,因此有很多问题哈哈,但到目前为止它已经很棒了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-27
  • 2017-02-17
  • 1970-01-01
相关资源
最近更新 更多