4

I am trying to pass an array of objects through angular template from one component to another one.

 <div *ngFor="let item of data">
    <div class="col-xl-3">
      <top-users  usersData ={{[item]}}> </top-users>
    </div>
  </div>

item here supposed to be

[{id:1, name: 'Ahmed'}, {id:2, name:'Mohammed'}]

and the data is array of array of objects

[    
 [{id:1, name: 'Ahmed'}, {id:2, name:'Mohammed'}],
 [{id:3, name: 'Ahmed'}, {id:4, name:'Mohammed'}],
 [{id:5, name: 'Ahmed'}, {id:6, name:'Mohammed'}]
]

When I receive the variable through @input parameter, I get the result typeof string and looks like this

[object Object],[object Object]

I tried to parseJson and gives me this error

ERROR SyntaxError: Unexpected token o in JSON at position 1

What should I do to get the right array of object?

1
  • I dont think [item] is a right way. it should be item. tried to keep it simple this will reduce bugs. Commented Apr 11, 2019 at 8:03

2 Answers 2

7

You need to pass the data as below :

<div *ngFor="let item of data">
    <div class="col-xl-3">
      <top-users  [usersData]="item"> </top-users>
    </div>
  </div>

You will receive in child component as:

@Input() usersData;

usersData will look like:

[{id:1, name: 'Ahmed'}, {id:2, name:'Mohammed'}]
Sign up to request clarification or add additional context in comments.

2 Comments

For completeness, the different flavors of Angular's template syntax are listed here.
I'd also add that when you use an attribute without square brackets, you are passing a literal string and that's fine. The problem is that he was interpolating an object
0

I had the same problem. I created the file with strict on, so I modified the strict to false in tsconfig.json file.

"compilerOptions": {
  "strict": false,

And also tried:

 "compilerOptions": {
   "noImplicitUseStrict": true, 

If you don't find strict just add it, don't forget to add comma(,) after "strict": false,. Next time create the file with -no--strict. ex. ng new fileName -no--strict

Comments

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.