如何知道ngOnChanges中的@Input变化? [英] How to know which @Input changes in ngOnChanges?
问题描述
我正在使用Angular 2.
I am using Angular 2.
现在我有两个@input aa
和bb
.我想做:
Right now I have two @input aa
and bb
. I want to do:
- 如果
aa
发生更改,请执行某些操作. - 如果
bb
发生更改,请执行其他操作.
- If
aa
changes, do something. - If
bb
changes, do other thing.
如何知道ngOnChanges
中的@Input发生了变化?谢谢
How to know which @Input changes in ngOnChanges
? Thanks
@Input() aa;
@Input() bb;
ngOnChanges(changes: { [propName: string]: SimpleChange }) {
// if aa changes, do something
// if bb changes, do other thing
}
推荐答案
可能可以这样做
ngOnChanges(changes: { [propName: string]: SimpleChange }) {
if( changes['aa'] && changes['aa'].previousValue != changes['aa'].currentValue ) {
// aa prop changed
}
if( changes['bb'] && changes['bb'].previousValue != changes['bb'].currentValue ) {
// bb prop changed
}
}
我很惊讶地定义了未更改的属性.从食谱中,我希望只能定义更改的属性.
I'm surprised that the unchanged properties are defined, though. From the cookbook, I would expect that only changed properties would be defined.
https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-on-changes
如果这太冗长,您也可以尝试使用setter方法:
If that is too verbose, you could also try using the setter approach:
_aa: string;
_bb: string;
@Input() set aa(value: string) {
this._aa = value;
// do something on 'aa' change
}
@Input() set bb(value: string) {
this._bb = value;
// do something on 'bb' change
}
https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-setter
这篇关于如何知道ngOnChanges中的@Input变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!