How to iterate over an array passed by an Input Decorator

2.7k Views Asked by At

I generate in my parent component an array of objects and I pass it through an input decorator to the child Component(Chart Element).

I declare my array chartValues and I iterate over the main data Object and take the values that I will need in my chart by pushing them into my chartValues Array.

chartValues : Array<Object>=[];

this.chartValues.push({ name: data.countryName, y: data.areaInSqKm });

Later I passed this chartValues through the input decorator like this and I receive it in the Child Component but I am not able to iterate over it and I cant reach keys or entries.

<chart #values [filter]="filters.metric" [values]="chartValues"></chart>

@Input() values: Array<Object>;

I don't know if I'm declaring wrong the Array Type because when I create an Array and I pass it always the type of the element is Object

[enter image description here]

3

There are 3 best solutions below

1
On BEST ANSWER

Have a look on this working plunkr. You don't need #values.
Any of these should work:

@Input() values: Array<Object>=[];
@Input() values: Array<Object>;
@Input() values: Array<Object>=new Array();
0
On

Just change it as

@Input()
 values: any;
1
On

One thing is really important to understand, the inputs of a component are not evaluated yet in its constructor. So you should init your "chartValues" in ngOnInit lifecycle

  ngOnInit(): void {
     ...
     this.chartValues.push({ name: data.countryName, y: data.areaInSqKm});      
}