强制 Angular 2 视图从数据更新
Force Angular 2 view to update from data
我有一个 Angular 2 (beta 0) 组件,其值根据 Angular 之外的代码而变化。我可以监听这个并在发生这种变化时执行代码,但我不知道什么代码 运行 强制 Angular 2 视图更新。
如果我在初始化组件时获取对 运行 的 NgZone 的引用,然后我可以调用 ngZone.run(function() { /* do nothing */});
并强制更新。但是,我不知道这是否是我应该做的事情,即使是,我也不确定获取对我应用的 ngZone 的引用的合法方法是什么。
我应该怎么做?
[edit] 在 Angular 1.x 中我会做 $scope.$apply()
但这不在 Angular 2. 其他人建议做 setTimeout(function() { /* do stuff */ })
但是它似乎没有被 NgZone 挂钩(它 是 被普通区域挂钩),因此不会触发更改检查。
我明白了。与 Angular 1 不同,并非所有组件的可注入依赖项都可以从参数名称中推断出来。在我的例子中,我可以访问 NgZone,然后像这样在区域中绑定更改:
customSelect = ng.core
.Component({
selector: 'custom-select',
templateUrl: 'select.html',
properties:[
'valueProperty:valueProperty',
'value:value',
'options:options'
]
})
.Class({
constructor:[ng.core.NgZone, function(zone) {
this.zone = zone;
}],
ngOnInit:function() {
this.unbindChanges = this.valueProperty.bindChanges(function() {
this.zone.run(function() {
this.value = this.valueProperty.currentValue();
}.bind(this));
}.bind(this));
},
ngOnDestroy:function() {
this.unbindChanges();
}
});
我有一个 Angular 2 (beta 0) 组件,其值根据 Angular 之外的代码而变化。我可以监听这个并在发生这种变化时执行代码,但我不知道什么代码 运行 强制 Angular 2 视图更新。
如果我在初始化组件时获取对 运行 的 NgZone 的引用,然后我可以调用 ngZone.run(function() { /* do nothing */});
并强制更新。但是,我不知道这是否是我应该做的事情,即使是,我也不确定获取对我应用的 ngZone 的引用的合法方法是什么。
我应该怎么做?
[edit] 在 Angular 1.x 中我会做 $scope.$apply()
但这不在 Angular 2. 其他人建议做 setTimeout(function() { /* do stuff */ })
但是它似乎没有被 NgZone 挂钩(它 是 被普通区域挂钩),因此不会触发更改检查。
我明白了。与 Angular 1 不同,并非所有组件的可注入依赖项都可以从参数名称中推断出来。在我的例子中,我可以访问 NgZone,然后像这样在区域中绑定更改:
customSelect = ng.core
.Component({
selector: 'custom-select',
templateUrl: 'select.html',
properties:[
'valueProperty:valueProperty',
'value:value',
'options:options'
]
})
.Class({
constructor:[ng.core.NgZone, function(zone) {
this.zone = zone;
}],
ngOnInit:function() {
this.unbindChanges = this.valueProperty.bindChanges(function() {
this.zone.run(function() {
this.value = this.valueProperty.currentValue();
}.bind(this));
}.bind(this));
},
ngOnDestroy:function() {
this.unbindChanges();
}
});