我正在使用Angular 2.
现在我有两个@input aa和bb.我想要做:
>如果aa发生变化,请做点什么.
>如果bb发生变化,请做其他事情.
如何知道ngOnChanges中哪些@Input更改?谢谢
@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 } }
不过,我对未定义的属性进行定义感到惊讶.从食谱中,我预计只会定义更改的属性.
https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-on-changes
如果这太冗长,您也可以尝试使用setter方法:
_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