Home > Software design >  How to pass an array to a child component in angular
How to pass an array to a child component in angular

Time:12-26

So I am able to pass a string to a child component but when I try to pass an array I get [object Object] as a string parameter.

Not sure why this is happening!

parent component html:

<app-channel-fields-list data="{{channelFields}}"></app-channel-fields-list>

Where channelFields is

const channelFields =[ { "name": "first_name", "description": "first name" } ]

Child component html:

{{data}}

<tr *ngFor=" hero in data">
    <td>{{hero.name}}</td>
</tr> 

Child component ts:

 @Input() data;
  ngOnInit() {
      console.log('data', this.data);  // this also prints [object Object], which is weird
  }

So, not really sure what the issue is since it works perfectly for passing strings but not arrays!

Here is a youtube video with what it actually looks like: https://www.youtube.com/watch?v=1gsmnoVhEig

I found a similar question: Angular passing array from parent to child component

But I can't get the dang thing to work.

CodePudding user response:

You are getting the error because its trying to interpolate the object into a string because of the curly brackets int the parent declaration. You need to pass the array as in the following.

<app-channel-fields-list [data]="channelFields"></app-channel-fields-list>

This will allow the array to be pased to the child component - then you can iterate over it as you are doing. Also - minor thing = tyou do not need quotes around the object keys.

const channelFields =[ { name: "first_name", description: "my description" } ]

also - when iterating using *ngFor - you should use

<tr *ngFor="let hero of data">
    <td>{{hero.name}}</td>
</tr> 
  • Related