Hitesh Kumar
Hitesh Kumar

Reputation: 3698

Angular 2: Ignore first trigger of ngOnChanges?

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);
  }

Upvotes: 12

Views: 23908

Answers (5)

crg
crg

Reputation: 4557

To check if any changes has been made here is what you could do :

  ngOnChanges(changes: SimpleChanges) {
    Object.keys(changes).forEach(key => {
      if (changes[key].previousValue != undefined) {
          // Do your stuff
      }
    })
  }

Upvotes: 0

Marcus Riemer
Marcus Riemer

Reputation: 7688

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.

Upvotes: 3

Nimish goel
Nimish goel

Reputation: 2761

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() ) {}
}

Upvotes: 2

Kyle Krzeski
Kyle Krzeski

Reputation: 6527

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
  }
}

Upvotes: 10

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657068

You can use

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

if(changes['prop'].isFirstChange()) {
}

Upvotes: 22

Related Questions