1

Sorry if the title is confusing, not sure how to word it. I am trying to call a function to get data and pass it to a child component.

parent.component.ts:

getData(arg: string[]) {
    let data: any[];

    // Do stuff here to get data

    return data;
}

parent.component.html:

<app-child [myData]="getData(['test'])"></app-child>

child.component.ts

export class ChildComponent {

    @Input() myData: any[];

    // Stuff here
}

child.component.html

<h3>{{ myData[0].test }}</h3>

However, when I run the application, I get an error saying that it Cannot read property '0' of undefined. What am I doing wrong? I don't want to create a variable to bind to [myData] because I would then have a lot of them. I will be using this function in other places as well.

Any help would be appreciated, thank you!

2
  • Is there any http request happening when getData() is called? Or subscription to any other service? Commented Jul 9, 2018 at 2:09
  • There is not. I found it weird too. Commented Jul 9, 2018 at 2:17

1 Answer 1

2

Your function parameter should not be with [],change it as

<app-child [myData]="getData('test')"></app-child>

and use safe navigation operator on the child to make sure the data is not emptyu

<h3>{{ myData[0]?.test }}</h3>
Sign up to request clarification or add additional context in comments.

3 Comments

I don't understand. Why remove []? The function takes an array. I still get the same error when I remove it.
if function takes an array you just need to use the array variable
I ended up using the implicit arguments variable. Not sure why it didn't work the other way. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.