Angular 2: Ignore first trigger ngOnChanges?

Is there a way for angular 2 to skip the first ngOnChanges trigger? I am currently using this naive approach to ignore it:

isFirst: boolean = true;

  ngOnChanges(changes: SimpleChanges) {
    if (this.isFirst) {
      this.isFirst = false;
      return;
    }
    console.log(changes);
  }

      

+3


source to share


2 answers


you can use

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



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

      

+4


source


To add to the previous answer and explain this in a little more detail ...

changes

is an array of objects that have changed. Therefore, if you have an input myInput

, you need to access that object in the changeset by doing changes['myInput']

. myInput

contains:

  • previousValue

    - the previous value of the object (before the change)
  • currentValue

    - the current value of the object that was changed
  • firstChange

    - boolean whether this is the first time the change was made (note that this will be true when the component initializes 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
  }
}

      

+2


source







All Articles