0

I created a Angular component "linechart" (selector: <app-linechart>) that contains a D3 chart. The data for this chart is passed from the parent component via one-way databinding.

<app-linechart [data]="LC1_Data"></app-linechart>

Within the linechart the data gets parsed etc. but I thought this would not affect the original data from the parent component.

But when I try to nest multiple linechart components in the parent, only one chart is drawn. D3 tells me the date property on the second chart is null.

   <app-linechart   [data]="LC1_Data" ></app-linechart> 
   <app-linechart   [data]="LC1_Data" ></app-linechart> 

The strange thing is when I do not pass the data from the parent but use a static array with the data within the linechart component, I can draw both charts without problem. So I think is has to do with the data binding somehow.

The chart within the linechart component gets drawn via a createChart() function in the ngOnChanges() lifecycle hook.

What could cause this issue? I really have no idea how to solve this issue...

Update: AJT_82's hint was exactly the problem. As I'm just dealing with json data, I could simply clone the array via:

 var clonedArray = JSON.parse(JSON.stringify(nodesArray))

as suggested here: How do you clone an Array of Objects in Javascript?

If there is a simple more efficient way, please let me know :-)

JohnnyD.
  • 41
  • 3
  • Short answer: Objects are mutable and passed by reference. – AT82 Nov 27 '17 at 11:35
  • yes, I was expecting something like that. what would be a workaround? Could I copy the data (not the reference) in a new variable somehow? – JohnnyD. Nov 27 '17 at 11:48
  • You would have to do a deep clone, quick dirty option is like you did. Other option is to use Observables :) https://stackoverflow.com/a/40539061/6294072 – AT82 Nov 27 '17 at 12:06

0 Answers0