如何在google事件监听器触发后更改angular2后更改视图?

时间:2015-07-11 01:01:41

标签: google-maps-api-3 angular

我试图在触发事件侦听器后更新视图。但是,未检测到更改,并且在检测到其他更改之前不会更新。

Counter
import {
  Component, View, bootstrap
} from 'angular2/angular2';

@Component({
  selector: 'app'
})
@View({
  template: '{{keyword}} <input id="keyword" /><br/><span (click)="update()">{{click}}</span>'
})
class App {
  keyword;
  autocomplete;
  click;
  
  constructor() {
    var _this = this;
    var input = (document.getElementById('keyword'));
    this.autocomplete = new google.maps.places.Autocomplete(input);
    google.maps.event.addListener(this.autocomplete, 'place_changed', function(){
      console.log('place change');
      _this.keyword = "updated text";
      _this.click = "not clicked";
    });
    this.keyword = "original text";
    this.click = "click me after selection is made to force change";
  }
  
  update() {
    console.log("click");
    this.click = "clicked";
  }
  
}

bootstrap(App);

如果更改输入中的位置,则左侧文本应更改。只有在检测到另一个更改后才会更改它,例如单击下面的文本。

我做错了什么,我该怎么做?

2 个答案:

答案 0 :(得分:34)

@jhadesdev带领我朝着正确的方向前进,而不是zone.runOutsideAngular()我需要zone.run()。以下是完整的javascript代码:

&#13;
&#13;
import {
  Component, View, bootstrap, NgZone
} from 'angular2/angular2';

@Component({
  selector: 'app'
})
@View({
  template: '{{keyword}} <input id="keyword" /><br/><span (click)="update()">{{click}}</span>'
})
class App {
  keyword;
  autocomplete;
  click;
  zone: NgZone;
  
  constructor(zone:NgZone) {
    this.zone = zone;
    var input = (document.getElementById('keyword'));
    this.autocomplete = new google.maps.places.Autocomplete(input);
    google.maps.event.addListener(this.autocomplete, 'place_changed', ()=>{
      this.zone.run(() => {
      console.log('place change');
      this.keyword = "updated text";
      this.click = "not clicked";
      });
    });
    this.keyword = "original text";
    this.click = "click me after selection is made to force change";
  }
  
  update() {
    console.log("click");
    this.click = "clicked";
  }
  
}

bootstrap(App);
&#13;
&#13;
&#13;

答案 1 :(得分:8)

我认为问题在于自动完成的选择框绝对位于页面的body元素的末尾,因此在Angular跟踪的区域之外(在div的内部,{ {1}}是)。

要更改此设置,请执行以下操作:

  • 添加一些CSS以相对定位选择框(使用app)使其保持在区域内

  • 使用NgZone

    手动触发更改检测
    !important