How to stop ngOnChanges Called before ngOnInit ()

In my angular application, I came across a situation where ngOnchanges should only be called when the inputs are associated with changes. so is there a way to stop ngOnChanges from executing before ngOnInit. Is there any way to do this. Thanks at Advance.

+16
source share
2 answers

You cannot prevent this behavior, but you can:

Use the topic:

class Foo implements OnChanges,OnInit{

  onChanges = new Subject<SimpleChanges>();

  ngOnInit(){
    this.onChanges.subscribe((data:SimpleChanges)=>{
      // only when inited
    });
  }

  ngOnChanges(changes:SimpleChanges){
    this.onChanges.next(changes);
  }

}

Use the boolean property:

class Foo implements OnChanges,OnInit{

  initialized=false;

  ngOnInit(){
    // do stuff
    this.initialized = true;
  }

  ngOnChanges(changes:SimpleChanges){
    if(this.initialized){
      // do stuff when ngOnInit has been called
    }
  }

}

Use API SimpleChanges

You can also check the method : SimpleChange.isFirstChange()

isFirstChange(): boolean Check if the new value is the first assigned value.

class Foo implements OnChanges,OnInit{

  @Input()
  bar:any;

  ngOnInit(){
    // do stuff
  }

  ngOnChanges(changes:SimpleChanges){
    if(!changes["bar"].isFirstChange()){
      // do stuff if this is not the initialization of "bar"
    }
  }

}
+23
source

, , OP, ngOnChanges() - .

, , ng:

<ng-template></ng-template>

ng-, ViewContainerRef # createComponent.

, - , ngOnChanges() ngOnInit().

0

Source: https://habr.com/ru/post/1673573/


All Articles