Reputation: 1
In Angular, I have a reusable autocomplete
list and I need to pass the selected option to another component where this custom component is called. However, the custom component is not called directly and there is another component between them as shown below:
Component A: --> Component B: --> Component C:
custom-autocomplete modal-component employee-component
Now there are 2 option I think:
1. I can pass the selected value from Component A to any component via a shared service. But I am not sure if it is a good idea to inject a service dependency to a reusable component.
2. I can pass the selected value to Component B via EventEmitter, but I do not know if it is possible or good idea to pass the emitted event from Component B to Component C. I think I can pass the received event and parameter as I pass via EventEmitter usually, but not sure if it is a good idea.
So, what should be done in this scenario?
Upvotes: 1
Views: 536
Reputation: 2325
In my opinion you should use a shared service in which you should have BehaviourSubject
type observable
. So whenever user will select any value form autocomplerte
so you can pass that selected option to your BehaviourSubject
observable
and then in your another component
you can subscribe to that BehaviourSubject
.
And if you want to use multiple reusable autocomplete
in one component
so while passing each autcomplete's
selected value you can pass a property named type
in which you will be sending your autocomplete
type.
Like you have your function like this
passDataToAnotherComponent(selectedOption: any, type: string){
this.dataService.passData({option : selectedOption, type: type})
}
So when you call your above function for city so you will be calling in your template like this
<select (change)="passDataToAnotherComponent($event, 'city')">
<option>City 1</option>
<option>City 2</option>
</select>
<select (change)="passDataToAnotherComponent($event, 'department')">
<option>department 1</option>
<option>department 2</option>
</select>
And then in your receiving component just do like this
ngOnInit(){
this.dataService.behaviourSubjectObservableVariable.subscribe(data => {
if(type === 'city){
// do somehting
}
if(type === 'department){
// do somehting
}
})
}
Just gave a rough example to make you understand.
Upvotes: 1