Im trying to send an object over router-link in angular 2. I create a person-profile component for every person object in my person array people and display them on my screen.
<div *ngFor="#person of people; #i = index">
<person-profile [person]="person"></person-profile>
</div>
The person-profile component displays several pieces of information contained in the person object. Im trying to send the entire person object from the person-profile component to a component named "map" using a router-link and passing the person object as a parameter.
<person-profile>
..code..
<tr>
<td class="category">Address</td>
<td>{{ person.visiting_address }}</td>
<td *ngIf="person.visiting_address"><a [routerLink]="['Map',{person:person}]">View on map</a></td>
</tr>
..code..
<person-profile>
In my map component i retrieve the object with:
var person = <any> routeParams.get('person');
The problem is that i get the same person every time in the map component regardless of which <person-profile>
i execute the router-link from. Its always the first person in the people list. The weird thing is that if i pass specific parameters from the person object it works. For instance, if i pass person.family_name instead of the the entire person object everything works but i want to send the entire object. Any suggestions?
Thanks!
For passing the data from the child component to the parent component, we have to create a callback function in the parent component and then pass the callback function to the child component as a prop. This callback function will retrieve the data from the child component.
Passing Values Using Props React components can access data from other components via props. Props are used to send data from one component to another. In the below example, the Hello component accepts a name prop. Similarly, JSON values can be passed inside the props.
What is the difference between [routerLink] and routerLink ? How should you use each one? They're the same directive. You use the first one to pass a dynamic value, and the second one to pass a static path as a string.
AFAIK there is no way to pass objects because the source of the RouterLink
class doesn't indicate any support for that and because the data needs to be presented in the URL string.
My suggestion is to pass an ID and share the users in a service that allows to fetch the concrete instance by ID.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With