在angular2,如何获得性能onChanges改变送来一个@input的对象上 [英] In angular2, how to get onChanges for properties changed on an object sent in for an @Input
问题描述
我有一个指令,并在其上是 @input
接受的类。
I have a directive and on it is an @Input
that accepts a class.
@Directive({selector: 'my-directive'})
@View({directives: [CORE_DIRECTIVES]})
export class MyDirective {
@Input() inputSettings : SettingsClass;
@Input() count : number;
onChanges(map) {
console.log('onChanges');
}
}
该指令在HTML中使用:
The directive is used in html:
...
<my-directive [input-settings]="settings" [count]="settings.count"></my-directive>
...
如果该settings.count改变则 onChanges
将闪光。如果设置类发生变化的任何其他财产,那么就不会触发。
If the settings.count is changed then the onChanges
will fire. If any other property on the settings class changes, then it will not fire.
如何可以检测是否有变化上设置任何财产?
How can I detect if there is a change to any property on settings?
推荐答案
角如果该对象已被更改为不同的对象将只注意到(即对象引用改变),所以 ngOnChanges()
不能用于解决您的问题。请参见维克多Savkin的博客文章了解详情。
Angular will only notice if the object has been changed to a different object (i.e., the object reference changed), so ngOnChanges()
can't be used to solve your problem. See Victor Savkin's blog post for more information.
您可以实现在MyDirective类 ngDoCheck()
方法。这种生命周期挂钩被称为一个组件或指令的输入性检查每次使用它通过执行自定义检查扩展变化检测。 - 从<一个href=\"https://github.com/angular/angular/blob/master/modules/angular2/docs/cheatsheet/lifecycle%20hooks.md\">lifecyle hooks.md
You could implement the ngDoCheck()
method in your MyDirective class. That lifecycle hook is called "every time that the input properties of a component or a directive are checked. Use it to extend change detection by performing a custom check" -- from lifecyle hooks.md
要实现自定义的检查方法,你首先需要实现 .equals()
的类方法 SettingsClass
这样,你可以再写入code像在以下ngDoCheck()
:
To implement your custom check method, you would first need to implement an .equals()
method on class SettingsClass
such that you could then write code something like the following in ngDoCheck()
:
ngDoCheck() {
if(!this.inputSettings.equals(this.previousInputSettings)) {
// inputSettings changed
// some logic here to react to the change
this.previousInputSettings = this.inputSettings;
}
}
这篇关于在angular2,如何获得性能onChanges改变送来一个@input的对象上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!