How to pass and receive a parameter between angular components

Asked

Viewed 2,359 times

2

I was passing the parameter Id using Routes:

const routes: Routes = [
  { path: '', redirectTo: 'sites', pathMatch: 'full' },
  { path: 'addSite', component: AddSiteComponent },
  { path: 'sites', component: ShowSitesComponent },
  { path: 'sites/editSite/:_id', component: EditSiteComponent }
];

That when passing the parameter site._id, it supposedly goes to the component editSite(I can see it in the URL) with this parameter, but I cannot receive the parameter value to use in the other component.

<button mat-raised-button color="primary">
    <a routerLink="editSite/{{site._id}}" style="text-decoration: none; color: white" routerLinkActive="active">Editar</a>
</button>

What should I put on to receive this id? or any other parameter.

  • i do so, in the init of the editing Component: if ( this.activatedRoute.snapshot.params && this.activatedRoute.snapshot.params.id ) { const id = this.activatedRoute.snapshot.params.id;}

1 answer

3


To receive a parameter in the component use

const _id = this.activatedRoute.snapshot.params._id;

Don’t forget to put in constructor

private activatedRoute: ActivatedRoute  
  • do you want to send the full object? without only id?

  • @Matheusribeiro It is not very safe to send the whole object for a "GET", but you can for example Encrypt to be smaller and send everything in the parameter and then in the component.

  • @Matheusribeiro The best way to send an entire object while switching pages is to use the Store, so by storing the objects in a local store in the user’s browser, you can get the entire object from the ID

  • 1

    @MatheusRibeiro https://ngrx.io/guide/store

  • 1

    I’ll take a look, thanks

  • To pass complex objects or values, I suggest you use a Resolve, see the Angular documentation link: https://angular.io/api/router/Resolve

  • Or Voce can cache this object using a shared service.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.