Is there any angular 2 way to skip the first trigger of ngOnChanges? Currently I am using this naive approach to ignore it:
isFirst: boolean = true;
ngOnChanges(changes: SimpleChanges) {
if (this.isFirst) {
this.isFirst = false;
return;
}
console.log(changes);
}
You can use
https://angular.io/docs/ts/latest/api/core/index/SimpleChange-class.html#!#isFirstChange-anchor
if(changes['prop'].isFirstChange()) {
}
To add onto the previous answer and explain this a bit more...
changes is an array of objects that have been changed. So if you have an input myInput, you'll need to access that object within the changes array by doing changes['myInput']. myInput contains:
previousValue - previous value of the object (before the change) currentValue - current value of the object that has been changedfirstChange - boolean on whether this is the first time there has
been a change (note this will be true when the component intializes
and false otherwise) - isFirstChange() will return true if this is the first change.Code:
//your input
@Input() myInput: any;
ngOnChanges(changes: any) {
//check if this isn't the first change of myInput
if(!changes['myInput'].isFirstChange()) {
//do something
}
}
If you have many inputs, but can't tell for sure which one of them is set, you may use
isFirstChange setngOnChanges(changes: SimpleChanges) {
const isFirstChange = Object.values(changes).some(c => c.isFirstChange());
}
Beware: If no @Input is set at all, isFirstChange will be false because Array.some stops at the first true value.
For a safer side, I always do this and it works like a charm.
ngOnChanges(changes: { [key: string]: SimpleChange }): void {
if (changes['propertyName'] &&
changes['propertyName'].previousValue !== undefined &&
!changes['propertyName'].isFirstChange() ) {}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With