I\'ve been trying to find a simple solution.
I have a for loop displaying a list of items. clicking on one of the items routes you to the detailed component and I just wa
Objects passing by routing is limited options. Using a service is the better option. If you provide a service instance by the parent component, then the same instance gets injected in parent and child and you have the shared data available immediately.
https://stackblitz.com/edit/angular-6-communicating-between-components-1gunkw?file=app%2Fapp.component.ts
From Angular 7.2 you can pass argument to router, see this great link
In .html you must use [state], e.g.
<div *ngFor="let item of items" [routerLink]="['/item-details']" [state]=item>
Two get the state you has two options, from a component not main-app, see this answer, from the main-app you can subscribe to router.events
this.router.events.pipe(
filter(e => e instanceof NavigationStart),
map(() => this.router.getCurrentNavigation().extras.state)
).subscribe((res:any)=>{
console.log(res)
})
NOTE: if use this aproach, remember that if you access directly to your "item-details.component", you has any "item"
you don't want to pay an object through a router. Instead pass an id and then re-look up the item on the new page. That way if you refresh the new page, everything still works.
Please try like this
<ul>
<li *ngFor="let product of products">
<a [routerLink]="['/product/',product.id]"></a>
</li>
</ul>
What i think about why there is no way to pass an object through a router is because if you pass the data and made it available on the route2
,
the data is available on the route2
just because it is passed from route1
.
What happens if you refresh route2
??
from where will you get the data for route2
, your page would collapse.