how to stop ngOnChanges Called before ngOnInit()

后端 未结 3 1800
南方客
南方客 2020-12-13 14:07

In my angular application, i came up with a situation where ngOnchanges should only be called when the inputs are bound to changes. so, is there a way to stop the execution

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 14:22

    You cannot prevent this behavior, but you can:

    Use a Subject :

    class Foo implements OnChanges,OnInit,OnDestroy{
    
      onChanges = new Subject();
    
      ngOnInit(){
        this.onChanges.subscribe((data:SimpleChanges)=>{
          // only when inited
        });
      }
      ngOnDestroy(){
        this.onChanges.complete();
      }
    
      ngOnChanges(changes:SimpleChanges){
        this.onChanges.next(changes);
      }
    
    }
    

    Use a 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 the SimpleChanges API

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

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

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

提交回复
热议问题