Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Ignore first trigger of ngOnChanges?

Tags:

angular

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);
  }
like image 429
Hitesh Kumar Avatar asked Apr 14 '17 06:04

Hitesh Kumar


4 Answers

You can use

https://angular.io/docs/ts/latest/api/core/index/SimpleChange-class.html#!#isFirstChange-anchor

if(changes['prop'].isFirstChange()) {
}
like image 146
Günter Zöchbauer Avatar answered Oct 17 '22 15:10

Günter Zöchbauer


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 changed
  • firstChange - 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
  }
}
like image 45
Kyle Krzeski Avatar answered Oct 17 '22 15:10

Kyle Krzeski


If you have many inputs, but can't tell for sure which one of them is set, you may use

  • Object.values to retrieve all changes as an array
  • Array.some to check whether any of the changes has isFirstChange set
ngOnChanges(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.

like image 33
Marcus Riemer Avatar answered Oct 17 '22 16:10

Marcus Riemer


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() ) {}
}
like image 2
Nimish goel Avatar answered Oct 17 '22 17:10

Nimish goel