I'm quite new to Angular 2 and I would like to transfer an array made in a parent component, via @Input(), to its child.
In the parent I create the array, add data from a service, and display it in the console (Console output 1). In the child component I then use ngOnChanges to display it in the console again (Console output 2). As you can see below, the length of the array changes from 12 to 0. I suppose this is because the array changes to an object when it's passed to the child?
How would I fix this?
Parent
import { Component, OnInit } from '@angular/core';
import { Module, MapMarkerData } from './coreclasses';
import { TimelineService } from './input.service';
@Component({
selector: 'my-app',
templateUrl: 'app/app.component.html',
providers: [TimelineService]
})
export class AppComponent implements OnInit {
modules: Module[];
mapMarkerData: any;
constructor(private timelineService: TimelineService) {
this.mapMarkerData = new Array<MapMarkerData>();
}
getModules(): void {
this.timelineService.getModules().then(modules => {this.modules = modules; this.setMapModuleData(this.modules);});
}
setMapModuleData(modules: Array<any>): void {
for (let module of modules) {
if (module.className) {
var id = module.id;
var className = module.className;
let contents: Object = {id: id, className: className};
this.mapMarkerData.push(contents);
}
}
console.log(this.mapMarkerData); // CONSOLE OUTPUT 1
console.log(this.mapMarkerData.length);
}
}
Child
import { Component, Input, OnInit, OnChanges, SimpleChanges } from '@angular/core';
import { MapMarkerData } from './coreclasses';
@Component({
selector: 'timeline-map',
templateUrl: 'app/timeline.map.component.html'
})
export class TimelineMapComponent implements OnChanges {
@Input()
mapMarkerData: any;
ngOnChanges(changes: any) {
console.log(this.mapMarkerData); // CONSOLE OUTPUT 2
console.log(this.mapMarkerData.length);
}
}
Parent Template
...
<div id="map" class="mapLarge">
<timeline-map [mapMarkerData] = "mapMarkerData"></timeline-map>
</div>
...
Console Output 1 Array[12]: [Object, Object, ... ]
Console Output 2 Array[0]: [Object, Object, ... ]