References to my answer is taken from the official documentation. Going through this link would help.
There can be different scenarios. Lets have a look at them.
- DetailComponent is the child of your current component
- DetailComponent is the sibling of your current component
- DetailComponent is the parent of your current component
Scenario 1: DetailComponent is the child of your current component
As described by @nguyen in his answer
Since you have defined @input decorator in your DetailComponent, if the DetailComponent is the child of your current component and the selector of your DetailComponent is suppose app-detail then in your html template you will call the detail component and pass the value
<app-detail[id]="selectedId"></app-detail>
provided selectedId is the class variable of your current component which holds the id that you want to pass to the DetailComponent
i.e suppose your function
findId(id:number){
console.log(id)
}
is working and you can see the id in console, then modify your function
findId(id:number){
console.log(id);
this.selectedId = id;
}
For Scenario 2 and Scenario 3 have a look at the documentation where you have the choice of either passing the values using event emitters.
Otherwise what I like to do is I create a service and that service holds the values that are common to multiple components. Then I import the service in the components that uses these values.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataStoreService {
selectedId: string;
}
In your Current Component:
export class CurrentComponent implements OnInit {
constructor(public dataStoreService: DataStoreService) { }
ngOnInit() {}
findId(id:number){
this.dataStoreService.selectedId = id;
}
}
Then in you DetailComponent import the service
export class DetailComponent implements OnInit {
constructor(public dataStoreService: DataStoreService) { }
ngOnInit() {}
}
And in your DetailComponent html template
<div>{{dataStoreService.selectedId}}</div>
if CurrentComponent and DetailComponent are siblings then they both will import this service and use the same variable as a model which will be updated or displayed by the components.
DetailComponent? Where will the component be put in the template?lirun the component and show it in appcomponent.html