I found valuable information for my response in the official documentation. Checking out this link would be beneficial.
There are various scenarios to consider, so let's explore them:
- If DetailComponent is the child of your current component
- If DetailComponent is the sibling of your current component
- If DetailComponent is the parent of your current component
Situation 1: DetailComponent is the child of your current component
As mentioned by @nguyen in his explanation, if DetailComponent is a child and you have used the @Input
decorator, you can pass values like this:
<app-detail[id]="selectedId"></app-detail>
Assuming that selectedId
is the variable in your current component holding the id you want to send to DetailComponent.
If your function works properly and you see the id in console with:
findId(id:number){
console.log(id);
this.selectedId = id;
}
For Situations 2 and 3, refer to the documentation for passing values using event emitters or consider creating a service to share common values among components.
In your Current Component:
export class CurrentComponent implements OnInit {
constructor(public dataStoreService: DataStoreService) { }
ngOnInit() {}
findId(id:number){
this.dataStoreService.selectedId = id;
}
}
Then in your DetailComponent, import the service as well:
export class DetailComponent implements OnInit {
constructor(public dataStoreService: DataStoreService) { }
ngOnInit() {}
}
In your DetailComponent html template:
<div>{{dataStoreService.selectedId}}</div>
If CurrentComponent and DetailComponent are siblings, they can both use the same shared variable from the service to update or display data collectively.