How can I trigger ngOnChanges only after every inp

2019-04-11 14:47发布

How can I trigger ngOnChanges only after every input values has been set in ngOnInit. My code -->

`ngOnInit() {
this.multiSelectorData.forEach(item=>{
            this.allItems.push(item.data);
        });
}
ngOnChanges(changes: SimpleChanges) {
        if(changes['dataReady'] && changes['dataReady'].currentValue) {
   console.log(this.allItems);
}`

I wont get the array I initialized in ngonit in ngonchanges because ngonchanges is called before ngonit, how can i check if all are initialized before checking ngonchanges?

1条回答
Anthone
2楼-- · 2019-04-11 15:15

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.

查看更多
登录 后发表回答