Passing an array data from parent to child component has brought up some interesting scenarios:
parent.component.html:
<child-component
...
[options]="students"
>
</child-component>
Status I: Setting the array on definition works perfectly fine, allowing me to access the array values in the child component.
parent.component.ts:
export class ParentComponent implements OnInit {
students: any[] = [
{ name: "Mary" },
{ name: "Marta" },
{ name: "Kelly" },
{ name: "John" },
{ name: "Shelley" },
{ name: "Frankstein" },
{ name: "Shierley" },
{ name: "Igor" }
];
}
child.component.ts:
export class ChildComponent implements OnInit {
@Input() options: any[]= [];
}
Status II: However, when I set the array using a method instead of the definition, the input value turns out to be null. I wanted to populate the array with data fetched from the server, leading to this issue. After troubleshooting, I realized that the problem lies not in asynchronous data retrieval but in the placement of the array definition. How can I ensure that the data is passed as its array values?
parent.component.ts:
export class ParentComponent implements OnInit {
students: any[] = [];
ngOnInit() {
this.getStudents();
}
getStudents() {
this.students = [
{ name: "Mary" },
{ name: "Marta" },
{ name: "Kelly" },
{ name: "John" },
{ name: "Shelley" },
{ name: "Frankstein" },
{ name: "Shierley" },
{ name: "Igor" }
];
}
Note: Initially, I tried assigning null to the students when defining it, but it resulted in an error and a null value exception in the child component. I explored lifecycle-related solutions like ngOnChanges and ngAfterViewInit, but the issue persisted.