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

How to update view after change in angular2 after google event listener fired?

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

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);
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css" />
    <script data-require="jquery@2.1.4" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script src="https://jspm.io/system.js"></script>
    <script src="https://code.angularjs.org/2.0.0-alpha.30/angular2.dev.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js??v=3.exp&libraries=places"></script>
  </head>

  <body>
    <app></app>
    
    <script>
      System.import('main');
    </script>
  </body>

</html>

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

我哪里做错了,我该如何做对?

我认为问题是自动完成的选择框绝对定位在页面主体元素的末尾,因此在 Angular 跟踪的区域之外(这是在 div 里面 app 所在的位置)。

要更改它,可以:

  • 添加一些 CSS 以相对定位选择框(使用 !important)使其留在区域内

  • 手动触发变化检测,使用NgZone:

    zone.run(() => {
      console.log('place change');
      _this.keyword = "updated text";
      _this.click = "not clicked";
    });
    

@jhadesdev 引导我朝着正确的方向前进,但我需要 zone.run() 而不是 zone.runOutsideAngular()。这是有效的完整 javascript 代码:

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);