how to stop ngOnChanges Called before ngOnInit()

后端 未结 3 1798
南方客
南方客 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:35

    One method I have found that works is based on the fact that the input values all have a previous value property. If the input has not previously been set then that value will be CD_INIT_VALUE (as a string). So you can make a condition that your block of code in ngOnChanges should only run if the previous value is not CD_INIT_VALUE. Here's an example for your case where you're testing ALL the input values:

    ngOnChanges(changes: SimpleChanges) {
      let initialized: boolean = true;
      for (let prop in changes) {
        if (changes[prop].previousValue.toString() === 'CD_INIT_VALUE') {
          initialized = false;
          //we can break here since if any item is not initialized
          //we will say the inputs are NOT initialized
          break;
        }
      }
    
      if (initialized) {
        //code you want to execute
      }    
    }
    

    There are probably more elegant solutions but I've found this works. This is probably too late to help you but may help others as when I googled this I found this question. The solution was something I figured out from debugging.

提交回复
热议问题