2

I'm trying to use the onChanges lifecycle hook which returns a SimpleChange object. Looking inside this object, I see 2 properties: currentValue and previousValue.

I'm passing an array of numbers to this hook, and trying to use currentValue, which shows type of Array. Here is a plunker for example. I am console logging out the object to see how to use it.

I tried checking the docs on SimpleChange but there isn't anymore information I can find.

My questions:

  1. Is there a way to parse this array? Is it even an Array?

  2. Am I incorrectly using this hook? I want to pass data to a custom directive which uses this data to create a chart using ng2-charts. Sort of related to this other stackoverflow answer but outside the constructor. The chart should build on data changes passed to the directive instead.

  3. Are there alternative objects besides SimpleChange that I can use? Any examples from blogs or articles?

  4. Any recommended resources to look at about SimpleChange and lifecycle hooks? The docs are a bit dry, and don't have many examples.

Thanks for reading! I'm sorry but I will be heading off for the night, but will check again in the morning.

Community
  • 1
  • 1
philip yoo
  • 2,462
  • 5
  • 22
  • 37

1 Answers1

1

check working - plunker

Note: You get undefined value because initial value is not set. Look plunker now. By the way, you can take benefit of Rest Operator which is ... with OnChanges like this,

ngOnChanges(...args: any[]) {  // isn't it so simple ?
        console.log('onChange fired');
        console.log('changing', args[0].storage);
        console.log('previous', args[0].storage.previousValue);
        console.log('current', args[0].storage.currentValue);
        console.log('previous value', args[0].storage.previousValue[0]);
        console.log('current value', args[0].storage.currentValue[0]);
 }
micronyks
  • 54,797
  • 15
  • 112
  • 146
  • Thank you! It looks like I needed to set `storage` to an empty array initially. I guess this trips me up a bit because I feel like I'm expecting `ngOnChanges` to trigger each time I click the button, which should set `storage` to an array of the inputs. I'll definitely be more careful on this type of thing in the future. Thank you for the explanation and examples! – philip yoo Mar 17 '16 at 13:13