Caio Sheperd
Caio Sheperd

Reputation: 23

how to send an ID from an array that is inside a *ngFor to another component in Angular

I have an array of items that I cycle using ngFor. I'm trying to send all its attributes to another component.

I tried using this code:

*ngFor='let item of listaPostagens
[routerLink]="['/post-detalhado', item.id]

And in the other component:

this.idPost = this.route.snapshot.params['id']

But I don't know what to do next. Any help is appreciated.

Upvotes: 1

Views: 765

Answers (1)

Paramjot Singh
Paramjot Singh

Reputation: 705

If want you to open a new component's view on the router link click, with data that is associated with the "id" parameter, try doing the following steps

  1. Register route in the "app-routing.module.ts" file.

    path : 'post-detalhado/:id', component:YourHandlerComponent   
    
  2. Inside the handler component, create a member method that will responsible for processing the "id" parameter.

    getHero(): void
    {
        const id = Number(this.route.snapshot.paramMap.get('id'));
        // use this id local variable for further processing you want to do.
        // may be you want to show data associated with id 
    }
    
  3. call member method inside ngOnInit event handler.

    ngOnInit(): void {
       this.getHero();
    }
    

Upvotes: 2

Related Questions