简体   繁体   中英

Send Angular Value to another component

In my app, I have a menu that routes content via ID but I also have a detailed view where the content should be displayed (via the same ID).

I'm trying to display objects by their ID via button click and I'm not sure how I could pass the ID value to the item-detail component for it to display the content by ID. All the data I need is made available in a service.

I already route via ID and this works fine

path: ':id',
component: ItemDetailComponent,
data:
{
    title: 'Item Detail',
}

item.component.html (menu component)

Here I trigger an event

<ng-container *ngFor="let item of items">
    <button (click)="getId(item.id);"></button>

item.component.ts (menu component)

Here I get the id of the object

getId(datavalue: number) 
{
      console.log(datavalue); 
}

When I click on the button I get the correct ID in my console log.

Now I want to display the content in the detailed view by ID but I'm not sure how I could pass the ID to this component.

item-detail.component.html Maybe something like this?

<div>
    <h2>Text Content</h2>
    <p>
        {{glossar[datavalue]?.textContent}}
    </p>
</div>

Any help appreciated!

If I understood you well, so you should pass the ID to the item-detail component as @Input() parameter for the component, something like this:

 @Input()
 id: number;

HTML:

<item-detail-component [id]="item.id"></item-detail-component>

And then inside the item-detail-component load data via that id to get there details.

Since you use the routing module, then you should use the routing.

<button [routerLink]="[item.id]" (click)="getId(item.id);"></button>

If you have correctly set up your routing with router outlets and correct routes, this should work.

In your component, use the activated route to get your ID

constructor(private route: ActivatedRoute) { this.id = route.snapshot.params.id; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM