user5871859
user5871859

Reputation:

Cannot pass data to child if it is not initialized on definition

I am passing an array data from parent to child component and I have encountered the following situations:

parent.component.html:

<child-component
     ...
    [options]="students"
>
</child-component>

Status I: When I set the array on definition, everything is ok and I can get the array values on 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 on a method instead of definition, I get the input value as null. Why I want to fill the array in a method is that I fill it by retrieving data from server. So, I struggled with this problem and finally found that the problem is not related to async data. It is related to this definition place. So, how can I perform the data can be passed by 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: I think assigning null to the students on defining it. But otherwise it throws error and I encounter null value exception on child. Maybe lifcel-ycle related problem, but I have already tried ngOnchanges, ngAfterViewInit, etc.

Upvotes: 0

Views: 1002

Answers (1)

Berk Kurkcuoglu
Berk Kurkcuoglu

Reputation: 1523

If you do not directly assign an object which is passed to a child component, initially the input will receive undefined or an empty array since you are assigning an empty array to students variable.

To avoid it use conditional rendering with ngIf:

<child-component
     *ngIf="students && students.length > 0"
    [options]="students"
>
</child-component>

Upvotes: 2

Related Questions