How to update view after change in angular2 after google event listener fired?
@jhadesdev led me in the right direction but instead of zone.runOutsideAngular()
I needed zone.run()
. Here's the full javascript code that worked:
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);
I think the problem is that the selection box of the autocomplete is being absolutely positioned at the end of the body element of the page, and so outside the zone that is being tracked by Angular (which is inside the div where the app
is).
To change this, either:
add some CSS to position the selection box relative (using
!important
) to make it stay inside the zonetrigger the change detection manually, using NgZone:
zone.run(() => { console.log('place change'); _this.keyword = "updated text"; _this.click = "not clicked";});