我试图在触发事件侦听器后更新视图。但是,未检测到更改,并且在检测到其他更改之前不会更新。
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);
如果更改输入中的位置,则左侧文本应更改。只有在检测到另一个更改后才会更改它,例如单击下面的文本。
我做错了什么,我该怎么做?
答案 0 :(得分:34)
@jhadesdev带领我朝着正确的方向前进,而不是zone.runOutsideAngular()
我需要zone.run()
。以下是完整的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);
&#13;
答案 1 :(得分:8)
我认为问题在于自动完成的选择框绝对位于页面的body元素的末尾,因此在Angular跟踪的区域之外(在div的内部,{ {1}}是)。
要更改此设置,请执行以下操作:
添加一些CSS以相对定位选择框(使用app
)使其保持在区域内
使用NgZone:
手动触发更改检测!important